grist-widget-sdk 0.2.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 (70) hide show
  1. package/CHANGELOG.md +730 -0
  2. package/LICENSE +15 -0
  3. package/README.md +249 -0
  4. package/dist/advanced.cjs +2749 -0
  5. package/dist/advanced.cjs.map +1 -0
  6. package/dist/advanced.d.cts +790 -0
  7. package/dist/advanced.d.ts +790 -0
  8. package/dist/advanced.js +825 -0
  9. package/dist/advanced.js.map +1 -0
  10. package/dist/chunk-64SVRWW7.js +758 -0
  11. package/dist/chunk-64SVRWW7.js.map +1 -0
  12. package/dist/chunk-BNBV24WM.js +479 -0
  13. package/dist/chunk-BNBV24WM.js.map +1 -0
  14. package/dist/chunk-ELGVOHFD.js +32 -0
  15. package/dist/chunk-ELGVOHFD.js.map +1 -0
  16. package/dist/chunk-GTTD5HPO.js +36 -0
  17. package/dist/chunk-GTTD5HPO.js.map +1 -0
  18. package/dist/chunk-JASMM2YC.js +243 -0
  19. package/dist/chunk-JASMM2YC.js.map +1 -0
  20. package/dist/chunk-PM3B4WYV.js +12 -0
  21. package/dist/chunk-PM3B4WYV.js.map +1 -0
  22. package/dist/chunk-QKXKZ27D.js +1189 -0
  23. package/dist/chunk-QKXKZ27D.js.map +1 -0
  24. package/dist/chunk-QZG7SNUG.js +463 -0
  25. package/dist/chunk-QZG7SNUG.js.map +1 -0
  26. package/dist/chunk-REV5AUXD.js +25 -0
  27. package/dist/chunk-REV5AUXD.js.map +1 -0
  28. package/dist/chunk-XE2SKNLH.js +1641 -0
  29. package/dist/chunk-XE2SKNLH.js.map +1 -0
  30. package/dist/create-grist-emulator-C_0I4wax.d.ts +80 -0
  31. package/dist/create-grist-emulator-DBS6gmiI.d.cts +80 -0
  32. package/dist/emulator/devtools.cjs +1367 -0
  33. package/dist/emulator/devtools.cjs.map +1 -0
  34. package/dist/emulator/devtools.d.cts +46 -0
  35. package/dist/emulator/devtools.d.ts +46 -0
  36. package/dist/emulator/devtools.js +480 -0
  37. package/dist/emulator/devtools.js.map +1 -0
  38. package/dist/emulator/testing.cjs +2061 -0
  39. package/dist/emulator/testing.cjs.map +1 -0
  40. package/dist/emulator/testing.d.cts +50 -0
  41. package/dist/emulator/testing.d.ts +50 -0
  42. package/dist/emulator/testing.js +124 -0
  43. package/dist/emulator/testing.js.map +1 -0
  44. package/dist/emulator/transports.cjs +1132 -0
  45. package/dist/emulator/transports.cjs.map +1 -0
  46. package/dist/emulator/transports.d.cts +37 -0
  47. package/dist/emulator/transports.d.ts +37 -0
  48. package/dist/emulator/transports.js +12 -0
  49. package/dist/emulator/transports.js.map +1 -0
  50. package/dist/emulator.cjs +1796 -0
  51. package/dist/emulator.cjs.map +1 -0
  52. package/dist/emulator.d.cts +107 -0
  53. package/dist/emulator.d.ts +107 -0
  54. package/dist/emulator.js +26 -0
  55. package/dist/emulator.js.map +1 -0
  56. package/dist/index.cjs +5511 -0
  57. package/dist/index.cjs.map +1 -0
  58. package/dist/index.d.cts +825 -0
  59. package/dist/index.d.ts +825 -0
  60. package/dist/index.js +2447 -0
  61. package/dist/index.js.map +1 -0
  62. package/dist/inline-CRwQQ-GW.d.cts +311 -0
  63. package/dist/inline-QitZwXKP.d.ts +311 -0
  64. package/dist/templates-BC7FoSdW.d.ts +24 -0
  65. package/dist/templates-DBq719O_.d.cts +24 -0
  66. package/dist/types-Fb2wplkv.d.cts +228 -0
  67. package/dist/types-Fb2wplkv.d.ts +228 -0
  68. package/dist/use-grist-widget-options-from-context-BFhQBGRY.d.ts +522 -0
  69. package/dist/use-grist-widget-options-from-context-qpFMdoBJ.d.cts +522 -0
  70. package/package.json +131 -0
@@ -0,0 +1,2749 @@
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
+ // src/sdk/advanced/index.ts
21
+ var advanced_exports = {};
22
+ __export(advanced_exports, {
23
+ GristHandshakeProvider: () => GristHandshakeProvider,
24
+ useGristAccessToken: () => useGristAccessToken,
25
+ useGristActions: () => useGristActions,
26
+ useGristAvailability: () => useGristAvailability,
27
+ useGristCapabilities: () => useGristCapabilities,
28
+ useGristHandshake: () => useGristHandshake,
29
+ useGristHandshakeContext: () => useGristHandshakeContext,
30
+ useGristHandshakeContextOptional: () => useGristHandshakeContextOptional,
31
+ useGristMappedRecord: () => useGristMappedRecord,
32
+ useGristNewRecord: () => useGristNewRecord,
33
+ useGristReady: () => useGristReady,
34
+ useGristRecord: () => useGristRecord,
35
+ useGristRecords: () => useGristRecords,
36
+ useGristRowsFromTable: () => useGristRowsFromTable,
37
+ useGristSection: () => useGristSection,
38
+ useGristTable: () => useGristTable,
39
+ useGristTableOps: () => useGristTableOps,
40
+ useGristWidgetOptions: () => useGristWidgetOptions,
41
+ useGristWidgetOptionsFromContext: () => useGristWidgetOptionsFromContext
42
+ });
43
+ module.exports = __toCommonJS(advanced_exports);
44
+
45
+ // src/sdk/internal/hooks/use-grist-core.ts
46
+ var import_react2 = require("react");
47
+
48
+ // src/sdk/internal/handshake/types.ts
49
+ var ZERO_GENERATION = 0;
50
+ function nextGeneration(current) {
51
+ return current + 1;
52
+ }
53
+ var MAPPING_SOURCE_PRIORITY = [
54
+ "section_api",
55
+ "stream_record",
56
+ "stream_records",
57
+ "stream_new_record"
58
+ ];
59
+ function initialGristSnapshot() {
60
+ return {
61
+ generation: ZERO_GENERATION,
62
+ lifecycle: { phase: "idle" },
63
+ link: { state: "connected", lastSuccessMs: null, missedPings: 0 },
64
+ authz: { state: "pending", declared: "read table" },
65
+ config: { mappings: { state: "not_declared" } },
66
+ sync: {
67
+ record: { state: "cold" },
68
+ records: { state: "cold" },
69
+ options: { state: "cold" },
70
+ newRecord: { state: "cold" },
71
+ currentTable: { state: "unknown" }
72
+ }
73
+ };
74
+ }
75
+
76
+ // src/sdk/internal/handshake/actions.ts
77
+ function hasGenerationStamp(action) {
78
+ return "generation" in action && typeof action.generation === "number";
79
+ }
80
+
81
+ // src/sdk/helpers/grist-mappings.ts
82
+ function asColumnSpec(entry) {
83
+ return typeof entry === "string" ? { name: entry } : entry;
84
+ }
85
+ function validateColumnMappings(spec, mappings) {
86
+ const missing = [];
87
+ const emptyMultiples = [];
88
+ if (!spec) return { ok: true, pending: false, missing, emptyMultiples };
89
+ const m = mappings ?? {};
90
+ for (const raw of spec) {
91
+ const col = asColumnSpec(raw);
92
+ if (col.optional) continue;
93
+ const value = m[col.name];
94
+ if (col.allowMultiple) {
95
+ if (value === void 0) {
96
+ missing.push(col.name);
97
+ } else if (!Array.isArray(value) || value.length === 0) {
98
+ emptyMultiples.push(col.name);
99
+ }
100
+ } else {
101
+ if (value === void 0 || value === null || value === "") missing.push(col.name);
102
+ }
103
+ }
104
+ return {
105
+ ok: missing.length === 0 && emptyMultiples.length === 0,
106
+ pending: false,
107
+ missing,
108
+ emptyMultiples
109
+ };
110
+ }
111
+
112
+ // src/sdk/internal/handshake/mapping-resolver.ts
113
+ var MappingResolver = class {
114
+ constructor(declared, generation) {
115
+ /** Latest accepted payload per source. */
116
+ this.payloads = /* @__PURE__ */ new Map();
117
+ /** Last resolved state, used to detect duplicate ingests. */
118
+ this.lastResolvedHash = null;
119
+ this.declared = declared;
120
+ this.currentGeneration = generation;
121
+ }
122
+ /**
123
+ * Replace the declared columns (e.g. user passed a new `columns` array to
124
+ * the provider). Clears accumulated payloads — they were validated against
125
+ * the previous declaration.
126
+ */
127
+ redeclare(declared, atGeneration) {
128
+ this.declared = declared;
129
+ this.currentGeneration = atGeneration;
130
+ this.payloads.clear();
131
+ this.lastResolvedHash = null;
132
+ }
133
+ /** Bump the active generation. Payloads from older generations are dropped. */
134
+ bumpGeneration(next) {
135
+ if (next <= this.currentGeneration) return;
136
+ this.currentGeneration = next;
137
+ for (const [src, p] of this.payloads) {
138
+ if (p.generation < next) this.payloads.delete(src);
139
+ }
140
+ this.lastResolvedHash = null;
141
+ }
142
+ /** Forget every payload and reset the hash. The declaration is preserved. */
143
+ reset() {
144
+ this.payloads.clear();
145
+ this.lastResolvedHash = null;
146
+ }
147
+ /** Cheap, deterministic snapshot for tests/debug. */
148
+ knownSources() {
149
+ return [...this.payloads.keys()];
150
+ }
151
+ /**
152
+ * Ingest one payload. Returns a {@link ResolveOutcome}:
153
+ * - `still_pending` — no payloads accepted yet.
154
+ * - `no_change/stale_*` — input generation is older than current.
155
+ * - `no_change/duplicate_payload` — input did not move the resolution.
156
+ * - `resolved` — new resolution differs from the previous one.
157
+ *
158
+ * Call {@link current} to read the latest resolution without affecting
159
+ * the duplicate-detection hash.
160
+ */
161
+ ingest(input) {
162
+ if (input.generation < this.currentGeneration) {
163
+ return { kind: "no_change", reason: "stale_generation" };
164
+ }
165
+ if (input.generation > this.currentGeneration) {
166
+ this.bumpGeneration(input.generation);
167
+ }
168
+ this.payloads.set(input.source, input);
169
+ const computed = this.compute();
170
+ if (computed === null) return { kind: "still_pending" };
171
+ const hash = computeMappingHash(
172
+ computed.mappings,
173
+ computed.state === "complete",
174
+ computed.source
175
+ );
176
+ if (hash === this.lastResolvedHash) {
177
+ return { kind: "no_change", reason: "duplicate_payload" };
178
+ }
179
+ this.lastResolvedHash = hash;
180
+ return { kind: "resolved", state: computed };
181
+ }
182
+ /**
183
+ * Return the resolver's current resolution (pure read). Equivalent to
184
+ * `ingest(...)` without mutating any state — used by tests and by the
185
+ * reducer when re-applying after `MAPPING_INVALIDATION_RESOLVE`.
186
+ */
187
+ current() {
188
+ const computed = this.compute();
189
+ if (computed === null) return { kind: "still_pending" };
190
+ return { kind: "resolved", state: computed };
191
+ }
192
+ /**
193
+ * Compute the current best mapping from accumulated payloads (pure).
194
+ *
195
+ * Priority: higher-priority sources **override** specific keys from
196
+ * lower-priority sources. Keys absent from a higher-priority source fall
197
+ * back to lower-priority sources. This matches the production behaviour
198
+ * where `sectionApi.mappings()` is authoritative for the keys it reports,
199
+ * but stream payloads can fill in keys the section_api hasn't reported yet.
200
+ */
201
+ compute() {
202
+ if (this.payloads.size === 0) return null;
203
+ const merged = {};
204
+ let latestReportedAt = 0;
205
+ const contributors = [];
206
+ for (const src of [...MAPPING_SOURCE_PRIORITY].reverse()) {
207
+ const p = this.payloads.get(src);
208
+ if (!p) continue;
209
+ contributors.push(src);
210
+ if (p.receivedAtMs > latestReportedAt) latestReportedAt = p.receivedAtMs;
211
+ if (p.payload === null) continue;
212
+ for (const [k, v] of Object.entries(p.payload)) {
213
+ merged[k] = v;
214
+ }
215
+ }
216
+ if (contributors.length === 0) return null;
217
+ const validation = validateColumnMappings(this.declared, merged);
218
+ const source = contributors.length === 1 ? contributors[0] : "merged";
219
+ if (validation.ok) {
220
+ return {
221
+ state: "complete",
222
+ declared: this.declared,
223
+ mappings: merged,
224
+ source,
225
+ reportedAtMs: latestReportedAt
226
+ };
227
+ }
228
+ return {
229
+ state: "incomplete",
230
+ declared: this.declared,
231
+ mappings: merged,
232
+ missing: validation.missing,
233
+ emptyMultiples: validation.emptyMultiples,
234
+ source,
235
+ reportedAtMs: latestReportedAt
236
+ };
237
+ }
238
+ };
239
+ function computeMappingHash(mappings, ok, source) {
240
+ const keys = Object.keys(mappings).sort();
241
+ const body = keys.map((k) => {
242
+ const v = mappings[k];
243
+ if (Array.isArray(v)) return `${k}=[${v.join(",")}]`;
244
+ return `${k}=${v ?? ""}`;
245
+ }).join("|");
246
+ return `${ok ? "OK" : "KO"}::${source}::${body}`;
247
+ }
248
+
249
+ // src/sdk/internal/handshake/access.ts
250
+ var ACCESS_RANK = {
251
+ none: 0,
252
+ "read table": 1,
253
+ full: 2
254
+ };
255
+ var GRIST_ACCESS_LEVELS = ["none", "read table", "full"];
256
+ function parseGristRequiredAccess(raw) {
257
+ if (!raw) return null;
258
+ return GRIST_ACCESS_LEVELS.includes(raw) ? raw : null;
259
+ }
260
+ function isAccessSufficient(granted, required) {
261
+ return ACCESS_RANK[granted] >= ACCESS_RANK[required];
262
+ }
263
+ function gristAccessLevelLabel(level) {
264
+ switch (level) {
265
+ case "none":
266
+ return "No document access";
267
+ case "read table":
268
+ return "Read selected table";
269
+ case "full":
270
+ return "Full document access";
271
+ }
272
+ }
273
+ function formatInsufficientAccessMessage(required, _granted) {
274
+ const need = gristAccessLevelLabel(required);
275
+ return `Set Access level to at least "${need}" in the Custom widget settings.`;
276
+ }
277
+
278
+ // src/sdk/internal/handshake/reducer.ts
279
+ function createReducerContext() {
280
+ return { resolver: null };
281
+ }
282
+ var DEFAULT_REDUCER_CONFIG = {
283
+ staleAfterMissed: 1,
284
+ lostAfterMissed: 3
285
+ };
286
+ function gristReducer(snapshot, action, ctx, config = DEFAULT_REDUCER_CONFIG) {
287
+ if (hasGenerationStamp(action) && action.generation < snapshot.generation) {
288
+ return snapshot;
289
+ }
290
+ switch (action.type) {
291
+ // -- Lifecycle --------------------------------------------------------
292
+ case "DETECT_START":
293
+ return reduceDetectStart(snapshot, action.atMs);
294
+ case "DETECT_TICK":
295
+ return reduceDetectTick(snapshot, action.attempts);
296
+ case "DETECT_AVAILABLE":
297
+ return reduceDetectAvailable(snapshot, action.atMs);
298
+ case "DETECT_TIMEOUT":
299
+ return reduceTerminate(snapshot, {
300
+ kind: "script_timeout",
301
+ attempts: action.attempts
302
+ }, action.atMs);
303
+ case "NOT_EMBEDDED":
304
+ return reduceTerminate(snapshot, { kind: "not_embedded" }, action.atMs);
305
+ case "NEGOTIATE_START":
306
+ return reduceNegotiateStart(snapshot, action.access, action.atMs);
307
+ case "NEGOTIATE_SUCCESS":
308
+ return reduceNegotiateSuccess(snapshot, action.access, action.grantedLevel, action.atMs);
309
+ case "NEGOTIATE_FAIL":
310
+ return reduceTerminate(snapshot, action.reason, action.atMs);
311
+ case "TERMINATE":
312
+ return reduceTerminate(snapshot, action.reason, action.atMs);
313
+ case "AUTHZ_REPORT":
314
+ return reduceAuthzReport(snapshot, action.level, action.atMs);
315
+ // -- Link -------------------------------------------------------------
316
+ case "RPC_SUCCESS":
317
+ case "HEARTBEAT_OK":
318
+ return reduceLinkSuccess(snapshot, action.atMs);
319
+ case "RPC_FAILURE":
320
+ case "HEARTBEAT_FAIL":
321
+ return reduceLinkFailure(snapshot, action.atMs, config);
322
+ // -- Generation -------------------------------------------------------
323
+ case "BUMP_GENERATION":
324
+ return reduceBumpGeneration(snapshot, ctx);
325
+ // -- Config / mappings -----------------------------------------------
326
+ case "MAPPING_DECLARE":
327
+ case "MAPPING_REPORT":
328
+ case "MAPPING_INVALIDATE":
329
+ case "MAPPING_INVALIDATION_RESOLVE":
330
+ case "MAPPING_TIMEOUT":
331
+ return reduceMapping(snapshot, action, ctx);
332
+ // -- Sync -------------------------------------------------------------
333
+ case "STREAM_RECEIVED":
334
+ case "STREAM_WARMING":
335
+ case "STREAM_STALE":
336
+ return reduceStream(snapshot, action);
337
+ case "CURRENT_TABLE_KNOWN":
338
+ return updateSync(snapshot, {
339
+ ...snapshot.sync,
340
+ currentTable: { state: "known", tableId: action.tableId, refreshing: false }
341
+ });
342
+ case "CURRENT_TABLE_REFRESH_START":
343
+ if (snapshot.sync.currentTable.state !== "known") return snapshot;
344
+ return updateSync(snapshot, {
345
+ ...snapshot.sync,
346
+ currentTable: { ...snapshot.sync.currentTable, refreshing: true }
347
+ });
348
+ case "CURRENT_TABLE_ERROR":
349
+ return updateSync(snapshot, {
350
+ ...snapshot.sync,
351
+ currentTable: { state: "errored", message: action.message, sinceMs: action.atMs }
352
+ });
353
+ default: {
354
+ const _exhaustive = action;
355
+ void _exhaustive;
356
+ return snapshot;
357
+ }
358
+ }
359
+ }
360
+ function reduceDetectStart(snapshot, atMs) {
361
+ if (snapshot.lifecycle.phase !== "idle") return snapshot;
362
+ return {
363
+ ...snapshot,
364
+ lifecycle: { phase: "detecting", attempts: 0, startedAtMs: atMs }
365
+ };
366
+ }
367
+ function reduceDetectTick(snapshot, attempts) {
368
+ if (snapshot.lifecycle.phase !== "detecting") return snapshot;
369
+ if (attempts === snapshot.lifecycle.attempts) return snapshot;
370
+ return {
371
+ ...snapshot,
372
+ lifecycle: { ...snapshot.lifecycle, attempts }
373
+ };
374
+ }
375
+ function reduceDetectAvailable(snapshot, atMs) {
376
+ if (snapshot.lifecycle.phase !== "detecting" && snapshot.lifecycle.phase !== "idle") {
377
+ return snapshot;
378
+ }
379
+ return {
380
+ ...snapshot,
381
+ lifecycle: {
382
+ phase: "negotiating",
383
+ access: snapshot.authz.declared,
384
+ startedAtMs: atMs
385
+ }
386
+ };
387
+ }
388
+ function reduceNegotiateStart(snapshot, access, atMs) {
389
+ if (snapshot.lifecycle.phase === "terminated") return snapshot;
390
+ return {
391
+ ...snapshot,
392
+ authz: { state: "pending", declared: access },
393
+ lifecycle: snapshot.lifecycle.phase === "online" ? snapshot.lifecycle : { phase: "negotiating", access, startedAtMs: atMs }
394
+ };
395
+ }
396
+ function authzDeclared(snapshot) {
397
+ return snapshot.authz.declared;
398
+ }
399
+ function reduceAuthzReport(snapshot, level, _atMs) {
400
+ if (snapshot.lifecycle.phase !== "online") return snapshot;
401
+ const declared = authzDeclared(snapshot);
402
+ if (isAccessSufficient(level, declared)) {
403
+ const previousLevel = snapshot.authz.state === "granted" ? snapshot.authz.level : null;
404
+ const widened = previousLevel !== null && ACCESS_RANK[level] > ACCESS_RANK[previousLevel];
405
+ const nextAuthz2 = {
406
+ state: "granted",
407
+ level,
408
+ declared,
409
+ widened
410
+ };
411
+ if (snapshot.authz.state === "granted" && snapshot.authz.level === nextAuthz2.level && snapshot.authz.declared === nextAuthz2.declared && snapshot.authz.widened === nextAuthz2.widened) {
412
+ return snapshot;
413
+ }
414
+ return { ...snapshot, authz: nextAuthz2 };
415
+ }
416
+ const message = formatInsufficientAccessMessage(declared, level);
417
+ const nextAuthz = { state: "denied", declared, message };
418
+ if (snapshot.authz.state === "denied" && snapshot.authz.declared === nextAuthz.declared && snapshot.authz.message === nextAuthz.message) {
419
+ return snapshot;
420
+ }
421
+ return { ...snapshot, authz: nextAuthz };
422
+ }
423
+ function reduceNegotiateSuccess(snapshot, access, grantedLevel, atMs) {
424
+ if (snapshot.lifecycle.phase === "terminated") return snapshot;
425
+ const previousLevel = snapshot.authz.state === "granted" ? snapshot.authz.level : null;
426
+ const widened = previousLevel !== null && ACCESS_RANK[grantedLevel] > ACCESS_RANK[previousLevel];
427
+ return {
428
+ ...snapshot,
429
+ authz: {
430
+ state: "granted",
431
+ level: grantedLevel,
432
+ declared: access,
433
+ widened
434
+ },
435
+ lifecycle: snapshot.lifecycle.phase === "online" ? snapshot.lifecycle : { phase: "online", sinceMs: atMs, declaredAccess: access },
436
+ link: { state: "connected", lastSuccessMs: atMs, missedPings: 0 }
437
+ };
438
+ }
439
+ function reduceTerminate(snapshot, reason, atMs) {
440
+ if (snapshot.lifecycle.phase === "terminated") return snapshot;
441
+ const lifecycle = { phase: "terminated", reason, atMs };
442
+ return { ...snapshot, lifecycle };
443
+ }
444
+ function reduceLinkSuccess(snapshot, atMs) {
445
+ if (snapshot.lifecycle.phase !== "online") return snapshot;
446
+ const link = { state: "connected", lastSuccessMs: atMs, missedPings: 0 };
447
+ if (snapshot.link.state === link.state && snapshot.link.lastSuccessMs === link.lastSuccessMs && snapshot.link.missedPings === link.missedPings) {
448
+ return snapshot;
449
+ }
450
+ return { ...snapshot, link };
451
+ }
452
+ function reduceLinkFailure(snapshot, _atMs, config) {
453
+ if (snapshot.lifecycle.phase !== "online") return snapshot;
454
+ const missed = snapshot.link.missedPings + 1;
455
+ let state = snapshot.link.state;
456
+ if (missed >= config.lostAfterMissed) state = "lost";
457
+ else if (missed >= config.staleAfterMissed) state = "stale";
458
+ return {
459
+ ...snapshot,
460
+ link: { state, lastSuccessMs: snapshot.link.lastSuccessMs, missedPings: missed }
461
+ };
462
+ }
463
+ function reduceBumpGeneration(snapshot, ctx) {
464
+ const next = nextGeneration(snapshot.generation);
465
+ ctx.resolver?.bumpGeneration(next);
466
+ return {
467
+ ...snapshot,
468
+ generation: next,
469
+ // Marking streams as warming again ensures hooks treat the data as
470
+ // "in transit" until a fresh event arrives under the new generation.
471
+ sync: {
472
+ ...snapshot.sync,
473
+ record: degradeForRefresh(snapshot.sync.record, snapshot.generation),
474
+ records: degradeForRefresh(snapshot.sync.records, snapshot.generation),
475
+ options: degradeForRefresh(snapshot.sync.options, snapshot.generation),
476
+ newRecord: degradeForRefresh(snapshot.sync.newRecord, snapshot.generation)
477
+ }
478
+ };
479
+ }
480
+ function degradeForRefresh(freshness, prevGeneration) {
481
+ if (freshness.state === "hot" && freshness.generation === prevGeneration) {
482
+ return { state: "stale", lastEventMs: freshness.lastEventMs, reason: "host_quiet" };
483
+ }
484
+ return freshness;
485
+ }
486
+ function reduceMapping(snapshot, action, ctx) {
487
+ switch (action.type) {
488
+ case "MAPPING_DECLARE": {
489
+ if (action.declared.length === 0) {
490
+ if (snapshot.config.mappings.state === "not_declared") return snapshot;
491
+ ctx.resolver = null;
492
+ return {
493
+ ...snapshot,
494
+ config: { mappings: { state: "not_declared" } }
495
+ };
496
+ }
497
+ if (!ctx.resolver) {
498
+ ctx.resolver = new MappingResolver(action.declared, snapshot.generation);
499
+ } else {
500
+ ctx.resolver.redeclare(action.declared, snapshot.generation);
501
+ }
502
+ return {
503
+ ...snapshot,
504
+ config: {
505
+ mappings: {
506
+ state: "pending",
507
+ declared: action.declared,
508
+ declaredAtMs: action.atMs
509
+ }
510
+ }
511
+ };
512
+ }
513
+ case "MAPPING_REPORT": {
514
+ if (!ctx.resolver) return snapshot;
515
+ const outcome = ctx.resolver.ingest({
516
+ source: action.source,
517
+ payload: action.payload,
518
+ receivedAtMs: action.atMs,
519
+ generation: action.generation
520
+ });
521
+ if (outcome.kind !== "resolved") return snapshot;
522
+ return applyResolved(snapshot, outcome.state);
523
+ }
524
+ case "MAPPING_INVALIDATE": {
525
+ const previous = snapshot.config.mappings;
526
+ if (previous.state !== "complete" && previous.state !== "incomplete") {
527
+ return snapshot;
528
+ }
529
+ return {
530
+ ...snapshot,
531
+ config: {
532
+ mappings: {
533
+ state: "invalidating",
534
+ previous,
535
+ sinceMs: action.atMs
536
+ }
537
+ }
538
+ };
539
+ }
540
+ case "MAPPING_INVALIDATION_RESOLVE": {
541
+ if (snapshot.config.mappings.state !== "invalidating") return snapshot;
542
+ if (!ctx.resolver) {
543
+ return {
544
+ ...snapshot,
545
+ config: { mappings: snapshot.config.mappings.previous }
546
+ };
547
+ }
548
+ const outcome = ctx.resolver.current();
549
+ if (outcome.kind !== "resolved") {
550
+ return {
551
+ ...snapshot,
552
+ config: { mappings: snapshot.config.mappings.previous }
553
+ };
554
+ }
555
+ return applyResolved(snapshot, outcome.state);
556
+ }
557
+ case "MAPPING_TIMEOUT": {
558
+ const previous = snapshot.config.mappings;
559
+ if (previous.state !== "pending") return snapshot;
560
+ return {
561
+ ...snapshot,
562
+ config: {
563
+ mappings: {
564
+ state: "unreported",
565
+ declared: previous.declared,
566
+ afterMs: action.atMs - previous.declaredAtMs
567
+ }
568
+ }
569
+ };
570
+ }
571
+ }
572
+ }
573
+ function applyResolved(snapshot, resolved) {
574
+ const existing = snapshot.config.mappings;
575
+ if ((existing.state === "complete" || existing.state === "incomplete") && sameResolved(existing, resolved)) {
576
+ return snapshot;
577
+ }
578
+ return { ...snapshot, config: { mappings: resolved } };
579
+ }
580
+ function sameResolved(a, b) {
581
+ if (a.state !== b.state) return false;
582
+ if (a.state !== "complete" && a.state !== "incomplete") return false;
583
+ if (a.source !== b.source) return false;
584
+ const ak = Object.keys(a.mappings);
585
+ const bk = Object.keys(b.mappings);
586
+ if (ak.length !== bk.length) return false;
587
+ for (const k of ak) {
588
+ const av = a.mappings[k];
589
+ const bv = b.mappings[k];
590
+ if (Array.isArray(av) && Array.isArray(bv)) {
591
+ if (av.length !== bv.length) return false;
592
+ for (let i = 0; i < av.length; i++) if (av[i] !== bv[i]) return false;
593
+ } else if (av !== bv) {
594
+ return false;
595
+ }
596
+ }
597
+ return true;
598
+ }
599
+ function reduceStream(snapshot, action) {
600
+ if (action.type === "CURRENT_TABLE_KNOWN" || action.type === "CURRENT_TABLE_REFRESH_START" || action.type === "CURRENT_TABLE_ERROR") {
601
+ return snapshot;
602
+ }
603
+ const stream = action.stream;
604
+ const current = snapshot.sync[stream];
605
+ if (action.type === "STREAM_WARMING") {
606
+ if (current.state === "warming" || current.state === "hot") return snapshot;
607
+ return updateStream(snapshot, stream, { state: "warming", sinceMs: action.atMs });
608
+ }
609
+ if (action.type === "STREAM_STALE") {
610
+ if (current.state !== "hot") return snapshot;
611
+ return updateStream(snapshot, stream, {
612
+ state: "stale",
613
+ lastEventMs: current.lastEventMs,
614
+ reason: action.reason
615
+ });
616
+ }
617
+ if (current.state === "hot" && current.generation === action.generation && current.payloadHash === action.payloadHash) {
618
+ return snapshot;
619
+ }
620
+ return updateStream(snapshot, stream, {
621
+ state: "hot",
622
+ lastEventMs: action.atMs,
623
+ generation: action.generation,
624
+ payloadHash: action.payloadHash
625
+ });
626
+ }
627
+ function updateStream(snapshot, stream, next) {
628
+ return {
629
+ ...snapshot,
630
+ sync: { ...snapshot.sync, [stream]: next }
631
+ };
632
+ }
633
+ function updateSync(snapshot, sync) {
634
+ return { ...snapshot, sync };
635
+ }
636
+
637
+ // src/sdk/internal/handshake/derive.ts
638
+ function deriveStatus(snapshot) {
639
+ const { lifecycle, authz, link } = snapshot;
640
+ if (lifecycle.phase === "idle" || lifecycle.phase === "detecting") return "booting";
641
+ if (lifecycle.phase === "negotiating") return "booting";
642
+ if (lifecycle.phase === "terminated") {
643
+ switch (lifecycle.reason.kind) {
644
+ case "script_timeout":
645
+ case "not_embedded":
646
+ return "unavailable";
647
+ case "host_rejected":
648
+ case "ready_failed":
649
+ case "ready_timeout":
650
+ case "manual_terminate":
651
+ return "error";
652
+ }
653
+ }
654
+ if (authz.state === "denied") return "error";
655
+ if (link.state === "lost") return "error";
656
+ return "ready";
657
+ }
658
+ function deriveErrorMessage(snapshot) {
659
+ if (snapshot.lifecycle.phase === "terminated") {
660
+ switch (snapshot.lifecycle.reason.kind) {
661
+ case "ready_failed":
662
+ return snapshot.lifecycle.reason.message;
663
+ case "ready_timeout":
664
+ return `Grist handshake timed out after ${snapshot.lifecycle.reason.afterMs}ms`;
665
+ case "host_rejected":
666
+ return snapshot.lifecycle.reason.message;
667
+ case "script_timeout":
668
+ return `Grist plugin API never loaded (${snapshot.lifecycle.reason.attempts} attempts)`;
669
+ case "not_embedded":
670
+ return "This page is not embedded in a Grist iframe";
671
+ case "manual_terminate":
672
+ return null;
673
+ }
674
+ }
675
+ if (snapshot.authz.state === "denied") {
676
+ return snapshot.authz.message ?? `Grist denied requested access (${snapshot.authz.declared})`;
677
+ }
678
+ if (snapshot.lifecycle.phase === "online" && snapshot.link.state === "lost") {
679
+ return `Grist link lost (${snapshot.link.missedPings} consecutive failures)`;
680
+ }
681
+ return null;
682
+ }
683
+ function deriveCapabilities(snapshot) {
684
+ const { lifecycle, authz, link, config, sync } = snapshot;
685
+ const online = lifecycle.phase === "online";
686
+ const granted = authz.state === "granted";
687
+ const grantedReadOrMore = granted && ACCESS_RANK[authz.level] >= ACCESS_RANK["read table"];
688
+ const grantedFull = granted && authz.level === "full";
689
+ const linkUsable = link.state !== "lost";
690
+ const canRead = online && linkUsable && grantedReadOrMore;
691
+ const canFetchTable = canRead && link.state === "connected";
692
+ const mappingsUsable = hasUsableMappings(config.mappings);
693
+ const missing = mappingsMissing(config.mappings);
694
+ const emptyMultiples = mappingsEmptyMultiples(config.mappings);
695
+ const canRender = canRead && mappingsUsable;
696
+ const canWriteRecords = canRender && grantedFull;
697
+ const canWriteSchema = canWriteRecords && sync.currentTable.state === "known";
698
+ const hasFreshSelection = canRead && sync.record.state === "hot" && config.mappings.state !== "invalidating";
699
+ return {
700
+ canRead,
701
+ canRender,
702
+ canWriteRecords,
703
+ canWriteSchema,
704
+ canFetchTable,
705
+ hasFreshSelection,
706
+ hasUsableMappings: mappingsUsable,
707
+ missingMappings: missing,
708
+ emptyMultipleMappings: emptyMultiples
709
+ };
710
+ }
711
+ function hasUsableMappings(state) {
712
+ if (state.state === "not_declared") return true;
713
+ if (state.state === "complete") return true;
714
+ if (state.state === "invalidating") {
715
+ return state.previous.state === "complete";
716
+ }
717
+ return false;
718
+ }
719
+ function mappingsMissing(state) {
720
+ if (state.state === "incomplete") return state.missing;
721
+ if (state.state === "invalidating" && state.previous.state === "incomplete") {
722
+ return state.previous.missing;
723
+ }
724
+ return EMPTY;
725
+ }
726
+ function mappingsEmptyMultiples(state) {
727
+ if (state.state === "incomplete") return state.emptyMultiples;
728
+ if (state.state === "invalidating" && state.previous.state === "incomplete") {
729
+ return state.previous.emptyMultiples;
730
+ }
731
+ return EMPTY;
732
+ }
733
+ var EMPTY = Object.freeze([]);
734
+
735
+ // src/sdk/internal/handshake-manager-context.ts
736
+ var import_react = require("react");
737
+
738
+ // src/sdk/internal/ready-singleton.ts
739
+ var ACCESS_RANK2 = {
740
+ none: 0,
741
+ "read table": 1,
742
+ full: 2
743
+ };
744
+ var inFlight = null;
745
+ var lastAccess = null;
746
+ function shouldReinit(next) {
747
+ if (!lastAccess) return true;
748
+ return ACCESS_RANK2[next] > ACCESS_RANK2[lastAccess];
749
+ }
750
+ function ensureGristReady(payload) {
751
+ const access = payload.requiredAccess ?? "read table";
752
+ if (inFlight && !shouldReinit(access)) return inFlight;
753
+ lastAccess = access;
754
+ const next = Promise.resolve().then(() => {
755
+ const result = grist.ready(payload);
756
+ return result instanceof Promise ? result : Promise.resolve();
757
+ });
758
+ inFlight = next.catch((err) => {
759
+ inFlight = null;
760
+ lastAccess = null;
761
+ throw err;
762
+ });
763
+ return inFlight;
764
+ }
765
+ function resetGristReadySingleton() {
766
+ inFlight = null;
767
+ lastAccess = null;
768
+ }
769
+
770
+ // src/sdk/internal/build-manager-options.ts
771
+ function buildManagerOptionsFromGristOptions(options) {
772
+ const opts = {
773
+ requiredAccess: options?.requiredAccess ?? "read table",
774
+ columns: options?.columns ?? [],
775
+ allowSelectBy: options?.allowSelectBy,
776
+ hasCustomOptions: options?.hasCustomOptions,
777
+ onEditOptions: options?.onEditOptions,
778
+ negotiate: {
779
+ readyImpl: (payload) => ensureGristReady(payload)
780
+ },
781
+ onBeforeReload: () => resetGristReadySingleton()
782
+ };
783
+ if (options?.availabilityMaxAttempts !== void 0 || options?.availabilityIntervalMs !== void 0) {
784
+ const interval = options?.availabilityIntervalMs ?? 1e3;
785
+ const max = options?.availabilityMaxAttempts ?? 10;
786
+ opts.detect = {
787
+ pollSequenceMs: Array.from({ length: max }, () => interval),
788
+ budgetMs: interval * max
789
+ };
790
+ }
791
+ return opts;
792
+ }
793
+
794
+ // src/sdk/internal/handshake/effects/detect.ts
795
+ var DEFAULT_POLL_SEQUENCE_MS = [
796
+ 200,
797
+ 200,
798
+ 400,
799
+ 400,
800
+ 800,
801
+ 1600,
802
+ 3200,
803
+ 5e3,
804
+ 5e3,
805
+ 5e3,
806
+ 5e3,
807
+ 5e3,
808
+ 5e3,
809
+ 5e3
810
+ ];
811
+ function defaultBudgetMs(hint) {
812
+ if (hint === "slow-2g" || hint === "2g") return 12e4;
813
+ if (hint === "3g") return 6e4;
814
+ return 3e4;
815
+ }
816
+ function startDetectEffect(env, dispatch, signal, options = {}) {
817
+ const sequence = options.pollSequenceMs ?? DEFAULT_POLL_SEQUENCE_MS;
818
+ const budgetMs = options.budgetMs ?? defaultBudgetMs(env.effectiveTypeHint());
819
+ const startedAt = env.now();
820
+ let attempts = 0;
821
+ let timer = null;
822
+ let cancelled = false;
823
+ signal.addEventListener("abort", () => {
824
+ cancelled = true;
825
+ if (timer !== null) env.clearTimeout(timer);
826
+ });
827
+ dispatch({ type: "DETECT_START", atMs: startedAt });
828
+ const tick = () => {
829
+ if (cancelled) return;
830
+ timer = null;
831
+ const probe = env.probeGrist();
832
+ if (probe !== null) {
833
+ if (probe.embedded) {
834
+ dispatch({ type: "DETECT_AVAILABLE", atMs: env.now() });
835
+ } else {
836
+ dispatch({ type: "NOT_EMBEDDED", atMs: env.now() });
837
+ }
838
+ return;
839
+ }
840
+ attempts += 1;
841
+ dispatch({ type: "DETECT_TICK", attempts, atMs: env.now() });
842
+ const elapsed = env.now() - startedAt;
843
+ if (elapsed >= budgetMs) {
844
+ dispatch({ type: "DETECT_TIMEOUT", attempts, atMs: env.now() });
845
+ return;
846
+ }
847
+ const next = sequence[Math.min(attempts - 1, sequence.length - 1)] ?? 1e3;
848
+ const remaining = budgetMs - elapsed;
849
+ timer = env.setTimeout(tick, Math.max(0, Math.min(next, remaining)));
850
+ };
851
+ tick();
852
+ return {
853
+ cancel() {
854
+ cancelled = true;
855
+ if (timer !== null) {
856
+ env.clearTimeout(timer);
857
+ timer = null;
858
+ }
859
+ }
860
+ };
861
+ }
862
+
863
+ // src/sdk/internal/handshake/effects/negotiate.ts
864
+ var DEFAULT_NEGOTIATE_TIMEOUT_MS = 3e4;
865
+ function startNegotiateEffect(env, dispatch, signal, payload, options = {}) {
866
+ const timeoutMs = options.timeoutMs ?? DEFAULT_NEGOTIATE_TIMEOUT_MS;
867
+ const access = payload.requiredAccess ?? "read table";
868
+ let settled = false;
869
+ let timer = null;
870
+ const settle = (next) => {
871
+ if (settled) return;
872
+ settled = true;
873
+ if (timer !== null) env.clearTimeout(timer);
874
+ if (signal.aborted) return;
875
+ next();
876
+ };
877
+ dispatch({ type: "NEGOTIATE_START", access, atMs: env.now() });
878
+ const grist2 = env.getGrist();
879
+ if (!grist2) {
880
+ settle(
881
+ () => dispatch({
882
+ type: "NEGOTIATE_FAIL",
883
+ reason: { kind: "ready_failed", message: "grist global missing at negotiate" },
884
+ atMs: env.now()
885
+ })
886
+ );
887
+ return { cancel: () => settle(() => {
888
+ }) };
889
+ }
890
+ timer = env.setTimeout(() => {
891
+ if (settled) return;
892
+ settle(
893
+ () => dispatch({
894
+ type: "NEGOTIATE_FAIL",
895
+ reason: { kind: "ready_timeout", afterMs: timeoutMs },
896
+ atMs: env.now()
897
+ })
898
+ );
899
+ }, timeoutMs);
900
+ const handleSuccess = (g) => {
901
+ if (!g.docApi) {
902
+ dispatch({
903
+ type: "NEGOTIATE_FAIL",
904
+ reason: { kind: "ready_failed", message: "grist.docApi missing after ready" },
905
+ atMs: env.now()
906
+ });
907
+ return;
908
+ }
909
+ dispatch({
910
+ type: "NEGOTIATE_SUCCESS",
911
+ access,
912
+ grantedLevel: access,
913
+ // host doesn't report effective level; widen later via authz events
914
+ atMs: env.now()
915
+ });
916
+ };
917
+ const handleFailure = (err) => {
918
+ const message = err instanceof Error ? err.message : String(err);
919
+ const reason = { kind: "ready_failed", message };
920
+ dispatch({ type: "NEGOTIATE_FAIL", reason, atMs: env.now() });
921
+ };
922
+ const readyImpl = options.readyImpl ?? ((p) => grist2.ready(p));
923
+ try {
924
+ const result = readyImpl(payload);
925
+ if (result && typeof result.then === "function") {
926
+ ;
927
+ result.then(
928
+ () => settle(() => handleSuccess(env.getGrist() ?? grist2)),
929
+ (err) => settle(() => handleFailure(err))
930
+ );
931
+ } else {
932
+ settle(() => handleSuccess(env.getGrist() ?? grist2));
933
+ }
934
+ } catch (err) {
935
+ settle(() => handleFailure(err));
936
+ }
937
+ signal.addEventListener("abort", () => settle(() => {
938
+ }));
939
+ return { cancel: () => settle(() => {
940
+ }) };
941
+ }
942
+
943
+ // src/sdk/helpers/grist-widget-interaction.ts
944
+ function parseGristWidgetLinkingInfo(raw) {
945
+ if (!raw || typeof raw !== "object" || !("asTarget" in raw)) return void 0;
946
+ const linking = raw;
947
+ return {
948
+ asTarget: linking.asTarget == null ? null : String(linking.asTarget),
949
+ asSource: Boolean(linking.asSource)
950
+ };
951
+ }
952
+ function normalizeWidgetInteraction(interaction) {
953
+ if (!interaction || typeof interaction !== "object") return interaction;
954
+ const raw = interaction;
955
+ const access_level = typeof raw.access_level === "string" ? raw.access_level : typeof raw.accessLevel === "string" ? raw.accessLevel : void 0;
956
+ const linking = parseGristWidgetLinkingInfo(raw.linking);
957
+ return {
958
+ ...interaction,
959
+ ...access_level ? { access_level } : {},
960
+ ...linking ? { linking } : {}
961
+ };
962
+ }
963
+
964
+ // src/sdk/internal/subscriptions.ts
965
+ var GristEvent = class {
966
+ constructor(bindOnce) {
967
+ this.bindOnce = bindOnce;
968
+ this.listeners = /* @__PURE__ */ new Set();
969
+ this.hasValue = false;
970
+ this.bind = null;
971
+ }
972
+ subscribe(listener) {
973
+ this.listeners.add(listener);
974
+ if (!this.bind) {
975
+ this.bind = () => {
976
+ this.bind = () => {
977
+ };
978
+ try {
979
+ this.bindOnce((value) => {
980
+ this.hasValue = true;
981
+ this.last = value;
982
+ for (const l of this.listeners) l(value);
983
+ });
984
+ } catch (err) {
985
+ if (typeof console !== "undefined") {
986
+ console.error("[lib/grist] failed to subscribe to Grist event:", err);
987
+ }
988
+ }
989
+ };
990
+ this.bind();
991
+ }
992
+ if (this.hasValue && this.last !== void 0) {
993
+ listener(this.last);
994
+ }
995
+ return () => {
996
+ this.listeners.delete(listener);
997
+ };
998
+ }
999
+ /** Last cached value (or `undefined` if no event has fired yet). */
1000
+ peek() {
1001
+ return this.last;
1002
+ }
1003
+ /** True once at least one event has fired. */
1004
+ get ready() {
1005
+ return this.hasValue;
1006
+ }
1007
+ /**
1008
+ * Test helper: fan out a payload without calling `grist.on*`.
1009
+ * Used to simulate hosts that reuse one record object and mutate it in place.
1010
+ */
1011
+ deliverForTests(value) {
1012
+ this.hasValue = true;
1013
+ this.last = value;
1014
+ for (const l of this.listeners) l(value);
1015
+ }
1016
+ /**
1017
+ * Test helper: forget the bound state and cached value. Lets a test swap
1018
+ * `window.grist` (e.g. via the emulator's `dispose()` + `createGristEmulator()`)
1019
+ * and re-bind cleanly on the next subscribe.
1020
+ */
1021
+ _resetForTests() {
1022
+ this.listeners.clear();
1023
+ this.hasValue = false;
1024
+ this.last = void 0;
1025
+ this.bind = null;
1026
+ }
1027
+ };
1028
+ var recordEvent = new GristEvent((emit) => {
1029
+ const deliver = (record, mappings) => {
1030
+ emit({ record, mappings });
1031
+ };
1032
+ grist.onRecord(
1033
+ (record, mappings) => {
1034
+ deliver(record, mappings ?? null);
1035
+ },
1036
+ { keepEncoded: false }
1037
+ );
1038
+ const fetchSelectedRecord = grist.fetchSelectedRecord ?? grist.docApi?.fetchSelectedRecord;
1039
+ if (typeof grist.on !== "function" || typeof fetchSelectedRecord !== "function") {
1040
+ return;
1041
+ }
1042
+ let lastRowId;
1043
+ grist.on("message", async (msg) => {
1044
+ if (!msg || typeof msg !== "object") return;
1045
+ const host = msg;
1046
+ if (!host.tableId || typeof host.rowId !== "number") return;
1047
+ if (host.rowId === lastRowId) return;
1048
+ lastRowId = host.rowId;
1049
+ try {
1050
+ const record = await fetchSelectedRecord(host.rowId, { keepEncoded: false });
1051
+ deliver(record, recordEvent.peek()?.mappings ?? null);
1052
+ } catch (err) {
1053
+ if (typeof console !== "undefined") {
1054
+ console.error("[grist-widget-sdk] fetchSelectedRecord on cursor message failed:", err);
1055
+ }
1056
+ }
1057
+ });
1058
+ });
1059
+ var recordsEvent = new GristEvent((emit) => {
1060
+ grist.onRecords(
1061
+ (records, mappings) => {
1062
+ emit({ records, mappings: mappings ?? null });
1063
+ },
1064
+ { keepEncoded: false, format: "rows" }
1065
+ );
1066
+ });
1067
+ var optionsEvent = new GristEvent((emit) => {
1068
+ grist.onOptions((options, interaction) => {
1069
+ const normalized = normalizeWidgetInteraction(
1070
+ interaction ?? null
1071
+ );
1072
+ emit({
1073
+ options: options ? { ...options } : null,
1074
+ interaction: normalized
1075
+ });
1076
+ });
1077
+ });
1078
+ var newRecordEvent = new GristEvent((emit) => {
1079
+ if (typeof grist.onNewRecord !== "function") return;
1080
+ grist.onNewRecord((mappings) => {
1081
+ emit({ mappings: mappings ?? null });
1082
+ });
1083
+ });
1084
+
1085
+ // src/sdk/internal/handshake/effects/subscriptions.ts
1086
+ function defaultSubscriptionsBinder(ctx) {
1087
+ const offs = [];
1088
+ offs.push(
1089
+ recordEvent.subscribe((payload) => {
1090
+ const hash = quickHash("record", payload);
1091
+ dispatchStream(ctx, "record", hash);
1092
+ ctx.onRecordPayload?.(payload.mappings ?? null);
1093
+ })
1094
+ );
1095
+ offs.push(
1096
+ recordsEvent.subscribe((payload) => {
1097
+ const hash = quickHash("records", payload);
1098
+ dispatchStream(ctx, "records", hash);
1099
+ ctx.onRecordsPayload?.(payload.mappings ?? null);
1100
+ })
1101
+ );
1102
+ offs.push(
1103
+ optionsEvent.subscribe((payload) => {
1104
+ const hash = quickHash("options", payload);
1105
+ dispatchStream(ctx, "options", hash);
1106
+ const level = parseGristRequiredAccess(payload.interaction?.access_level);
1107
+ if (level !== null) {
1108
+ ctx.dispatch({
1109
+ type: "AUTHZ_REPORT",
1110
+ level,
1111
+ atMs: Date.now(),
1112
+ generation: ctx.getGeneration()
1113
+ });
1114
+ }
1115
+ ctx.onOptionsPayload?.(payload.options ?? null);
1116
+ })
1117
+ );
1118
+ offs.push(
1119
+ newRecordEvent.subscribe((payload) => {
1120
+ const hash = quickHash("newRecord", payload);
1121
+ dispatchStream(ctx, "newRecord", hash);
1122
+ ctx.onNewRecordPayload?.(payload.mappings ?? null);
1123
+ })
1124
+ );
1125
+ return {
1126
+ cancel() {
1127
+ for (const off of offs.splice(0)) off();
1128
+ }
1129
+ };
1130
+ }
1131
+ function dispatchStream(ctx, stream, payloadHash) {
1132
+ ctx.dispatch({
1133
+ type: "STREAM_RECEIVED",
1134
+ stream,
1135
+ payloadHash,
1136
+ atMs: Date.now(),
1137
+ generation: ctx.getGeneration()
1138
+ });
1139
+ }
1140
+ function quickHash(kind, payload) {
1141
+ return `${kind}::${stableSerialize(payload)}`;
1142
+ }
1143
+ function stableSerialize(value) {
1144
+ if (value === null) return "null";
1145
+ if (value === void 0) return "undefined";
1146
+ const t = typeof value;
1147
+ if (t === "number" || t === "string" || t === "boolean") return JSON.stringify(value);
1148
+ if (Array.isArray(value)) {
1149
+ return `[${value.map(stableSerialize).join(",")}]`;
1150
+ }
1151
+ if (t === "object") {
1152
+ const obj = value;
1153
+ const keys = Object.keys(obj).sort();
1154
+ const body = keys.map((k) => `${JSON.stringify(k)}:${stableSerialize(obj[k])}`).join(",");
1155
+ return `{${body}}`;
1156
+ }
1157
+ return String(value);
1158
+ }
1159
+
1160
+ // src/sdk/internal/handshake/effects/mappings.ts
1161
+ var DEFAULT_MAPPING_TIMEOUT_MS = 5e3;
1162
+ function startMappingsEffect(env, dispatch, signal, declared, getGeneration, options = {}) {
1163
+ let timeoutHandle = null;
1164
+ let cancelled = false;
1165
+ const startMs = env.now();
1166
+ dispatch({ type: "MAPPING_DECLARE", declared, atMs: startMs, generation: getGeneration() });
1167
+ if (declared.length === 0) {
1168
+ return {
1169
+ ingestStreamPayload: () => {
1170
+ },
1171
+ refetchSectionApi: async () => {
1172
+ },
1173
+ cancel: () => {
1174
+ }
1175
+ };
1176
+ }
1177
+ const timeoutMs = options.timeoutMs ?? DEFAULT_MAPPING_TIMEOUT_MS;
1178
+ timeoutHandle = env.setTimeout(() => {
1179
+ if (cancelled || signal.aborted) return;
1180
+ dispatch({ type: "MAPPING_TIMEOUT", atMs: env.now(), generation: getGeneration() });
1181
+ }, timeoutMs);
1182
+ signal.addEventListener("abort", () => {
1183
+ cancelled = true;
1184
+ if (timeoutHandle !== null) env.clearTimeout(timeoutHandle);
1185
+ });
1186
+ const ingestPayload = (source, raw) => {
1187
+ if (cancelled || signal.aborted) return;
1188
+ const payload = coerceMappingsPayload(raw);
1189
+ dispatch({
1190
+ type: "MAPPING_REPORT",
1191
+ source,
1192
+ payload,
1193
+ atMs: env.now(),
1194
+ generation: getGeneration()
1195
+ });
1196
+ };
1197
+ const refetchSectionApi = async () => {
1198
+ if (cancelled || signal.aborted) return;
1199
+ const grist2 = env.getGrist();
1200
+ const api = grist2?.sectionApi;
1201
+ if (!api || typeof api.mappings !== "function") return;
1202
+ try {
1203
+ const payload = await api.mappings();
1204
+ ingestPayload("section_api", payload);
1205
+ } catch {
1206
+ ingestPayload("section_api", null);
1207
+ }
1208
+ };
1209
+ void refetchSectionApi();
1210
+ return {
1211
+ ingestStreamPayload: (source, payload) => ingestPayload(source, payload),
1212
+ refetchSectionApi,
1213
+ cancel() {
1214
+ cancelled = true;
1215
+ if (timeoutHandle !== null) env.clearTimeout(timeoutHandle);
1216
+ }
1217
+ };
1218
+ }
1219
+ function coerceMappingsPayload(raw) {
1220
+ if (raw === null || raw === void 0) return null;
1221
+ if (typeof raw !== "object") return null;
1222
+ return raw;
1223
+ }
1224
+
1225
+ // src/sdk/internal/handshake/effects/heartbeat.ts
1226
+ var DEFAULT_HEARTBEAT_INTERVAL_MS = 3e4;
1227
+ var DEFAULT_HEARTBEAT_PING_TIMEOUT_MS = 1e4;
1228
+ function startHeartbeatEffect(env, dispatch, signal, options = {}) {
1229
+ const intervalMs = options.intervalMs ?? DEFAULT_HEARTBEAT_INTERVAL_MS;
1230
+ const pingTimeoutMs = options.pingTimeoutMs ?? DEFAULT_HEARTBEAT_PING_TIMEOUT_MS;
1231
+ const pauseWhenHidden = options.pauseWhenHidden ?? true;
1232
+ const probe = options.probe ?? defaultProbe(env);
1233
+ let cancelled = false;
1234
+ let paused = false;
1235
+ let intervalTimer = null;
1236
+ let inFlight3 = false;
1237
+ let inFlightTimeoutTimer = null;
1238
+ const clearInterval = () => {
1239
+ if (intervalTimer !== null) {
1240
+ env.clearTimeout(intervalTimer);
1241
+ intervalTimer = null;
1242
+ }
1243
+ };
1244
+ const clearInFlightTimeout = () => {
1245
+ if (inFlightTimeoutTimer !== null) {
1246
+ env.clearTimeout(inFlightTimeoutTimer);
1247
+ inFlightTimeoutTimer = null;
1248
+ }
1249
+ };
1250
+ const scheduleNext = (delay = intervalMs) => {
1251
+ clearInterval();
1252
+ if (cancelled || paused) return;
1253
+ intervalTimer = env.setTimeout(ping, delay);
1254
+ };
1255
+ const ping = () => {
1256
+ if (cancelled || paused) return;
1257
+ intervalTimer = null;
1258
+ if (inFlight3) {
1259
+ return;
1260
+ }
1261
+ inFlight3 = true;
1262
+ inFlightTimeoutTimer = env.setTimeout(() => {
1263
+ if (!inFlight3) return;
1264
+ inFlight3 = false;
1265
+ clearInFlightTimeout();
1266
+ if (!cancelled) {
1267
+ dispatch({ type: "HEARTBEAT_FAIL", atMs: env.now() });
1268
+ scheduleNext();
1269
+ }
1270
+ }, pingTimeoutMs);
1271
+ const handleOk = () => {
1272
+ if (!inFlight3) return;
1273
+ inFlight3 = false;
1274
+ clearInFlightTimeout();
1275
+ if (cancelled) return;
1276
+ dispatch({ type: "HEARTBEAT_OK", atMs: env.now() });
1277
+ scheduleNext();
1278
+ };
1279
+ const handleFail = () => {
1280
+ if (!inFlight3) return;
1281
+ inFlight3 = false;
1282
+ clearInFlightTimeout();
1283
+ if (cancelled) return;
1284
+ dispatch({ type: "HEARTBEAT_FAIL", atMs: env.now() });
1285
+ scheduleNext();
1286
+ };
1287
+ let result;
1288
+ try {
1289
+ result = probe();
1290
+ } catch {
1291
+ handleFail();
1292
+ return;
1293
+ }
1294
+ if (result && typeof result.then === "function") {
1295
+ ;
1296
+ result.then(handleOk, handleFail);
1297
+ } else {
1298
+ handleOk();
1299
+ }
1300
+ };
1301
+ const offVisibility = pauseWhenHidden && env.onVisibilityChange ? env.onVisibilityChange((visible) => {
1302
+ if (cancelled) return;
1303
+ if (visible) {
1304
+ if (paused) {
1305
+ paused = false;
1306
+ ping();
1307
+ }
1308
+ } else {
1309
+ paused = true;
1310
+ clearInterval();
1311
+ }
1312
+ }) : null;
1313
+ const offOnline = env.onOnline?.(() => {
1314
+ if (cancelled || paused) return;
1315
+ ping();
1316
+ }) ?? null;
1317
+ signal.addEventListener("abort", () => {
1318
+ cancelled = true;
1319
+ clearInterval();
1320
+ clearInFlightTimeout();
1321
+ inFlight3 = false;
1322
+ offVisibility?.();
1323
+ offOnline?.();
1324
+ });
1325
+ scheduleNext();
1326
+ return {
1327
+ cancel() {
1328
+ cancelled = true;
1329
+ clearInterval();
1330
+ clearInFlightTimeout();
1331
+ inFlight3 = false;
1332
+ offVisibility?.();
1333
+ offOnline?.();
1334
+ },
1335
+ recordRpcSuccess() {
1336
+ if (cancelled || paused) return;
1337
+ dispatch({ type: "RPC_SUCCESS", atMs: env.now() });
1338
+ scheduleNext();
1339
+ },
1340
+ recordRpcFailure() {
1341
+ if (cancelled || paused) return;
1342
+ dispatch({ type: "RPC_FAILURE", atMs: env.now(), kind: "other" });
1343
+ scheduleNext(Math.min(intervalMs, 1e3));
1344
+ },
1345
+ pingNow() {
1346
+ if (cancelled) return;
1347
+ ping();
1348
+ }
1349
+ };
1350
+ }
1351
+ function defaultProbe(env) {
1352
+ return async () => {
1353
+ const g = env.getGrist();
1354
+ if (!g) throw new Error("grist global missing");
1355
+ const docApi = g.docApi;
1356
+ if (!docApi || typeof docApi.getDocName !== "function") {
1357
+ throw new Error("grist.docApi.getDocName unavailable");
1358
+ }
1359
+ return docApi.getDocName();
1360
+ };
1361
+ }
1362
+
1363
+ // src/sdk/internal/handshake/authz-from-options-cache.ts
1364
+ function denyAuthzFromCachedOptionsIfInsufficient(snapshot, dispatch, env) {
1365
+ if (snapshot.lifecycle.phase !== "online") return;
1366
+ if (snapshot.authz.state === "denied") return;
1367
+ const payload = optionsEvent.peek();
1368
+ const level = parseGristRequiredAccess(payload?.interaction?.access_level);
1369
+ if (level === null) return;
1370
+ const declared = snapshot.authz.declared;
1371
+ if (isAccessSufficient(level, declared)) return;
1372
+ dispatch({
1373
+ type: "AUTHZ_REPORT",
1374
+ level,
1375
+ atMs: env.now(),
1376
+ generation: snapshot.generation
1377
+ });
1378
+ }
1379
+
1380
+ // src/sdk/internal/handshake/environment.ts
1381
+ function createBrowserEnvironment() {
1382
+ return {
1383
+ now: () => typeof performance !== "undefined" ? performance.now() : Date.now(),
1384
+ setTimeout: (cb, ms) => globalThis.setTimeout(cb, ms),
1385
+ clearTimeout: (h) => globalThis.clearTimeout(h),
1386
+ probeGrist() {
1387
+ if (typeof globalThis === "undefined") return null;
1388
+ const g = globalThis.grist;
1389
+ if (typeof g === "undefined") return null;
1390
+ const embedded2 = typeof window === "undefined" ? false : window.self !== window.top;
1391
+ return { embedded: embedded2 };
1392
+ },
1393
+ getGrist() {
1394
+ const g = globalThis.grist;
1395
+ return g ?? null;
1396
+ },
1397
+ effectiveTypeHint() {
1398
+ if (typeof navigator === "undefined") return null;
1399
+ const conn = navigator.connection;
1400
+ const t = conn?.effectiveType;
1401
+ if (t === "slow-2g" || t === "2g" || t === "3g" || t === "4g" || t === "5g") return t;
1402
+ return null;
1403
+ },
1404
+ onVisibilityChange(listener) {
1405
+ if (typeof document === "undefined") return () => {
1406
+ };
1407
+ const handler = () => listener(document.visibilityState === "visible");
1408
+ document.addEventListener("visibilitychange", handler);
1409
+ return () => document.removeEventListener("visibilitychange", handler);
1410
+ },
1411
+ onOnline(listener) {
1412
+ if (typeof window === "undefined") return () => {
1413
+ };
1414
+ const handler = () => listener();
1415
+ window.addEventListener("online", handler);
1416
+ return () => window.removeEventListener("online", handler);
1417
+ }
1418
+ };
1419
+ }
1420
+
1421
+ // src/sdk/internal/handshake/manager.ts
1422
+ function createGristHandshakeManager(options = {}) {
1423
+ const env = options.env ?? createBrowserEnvironment();
1424
+ const reducerConfig = {
1425
+ ...DEFAULT_REDUCER_CONFIG,
1426
+ ...options.reducerConfig ?? {}
1427
+ };
1428
+ let snapshot = initialGristSnapshot();
1429
+ const ctx = createReducerContext();
1430
+ const listeners = /* @__PURE__ */ new Set();
1431
+ let started = false;
1432
+ let abort = null;
1433
+ let detectHandle = null;
1434
+ let negotiateHandle = null;
1435
+ let subscriptionsHandle = null;
1436
+ let mappingsHandle = null;
1437
+ let heartbeatHandle = null;
1438
+ let recheckAuthzFromCacheAfterOnline = false;
1439
+ const declared = options.columns ?? [];
1440
+ const subscriptionsBinder = options.subscriptionsBinder ?? defaultSubscriptionsBinder;
1441
+ const notify = () => {
1442
+ for (const l of listeners) {
1443
+ try {
1444
+ l();
1445
+ } catch (err) {
1446
+ options.onError?.(err, "listener");
1447
+ }
1448
+ }
1449
+ };
1450
+ const dispatch = (action) => {
1451
+ const prev = snapshot;
1452
+ const next = gristReducer(prev, action, ctx, reducerConfig);
1453
+ if (next !== prev) {
1454
+ snapshot = next;
1455
+ onTransition(prev, next);
1456
+ notify();
1457
+ }
1458
+ };
1459
+ const onTransition = (prev, next) => {
1460
+ if (prev.lifecycle.phase !== "negotiating" && next.lifecycle.phase === "negotiating") {
1461
+ launchNegotiate();
1462
+ launchSubscriptions();
1463
+ }
1464
+ if (prev.lifecycle.phase !== "online" && next.lifecycle.phase === "online") {
1465
+ launchMappings();
1466
+ launchHeartbeat();
1467
+ if (recheckAuthzFromCacheAfterOnline) {
1468
+ recheckAuthzFromCacheAfterOnline = false;
1469
+ denyAuthzFromCachedOptionsIfInsufficient(next, dispatch, env);
1470
+ }
1471
+ }
1472
+ if (prev.lifecycle.phase === "online" && next.lifecycle.phase !== "online") {
1473
+ heartbeatHandle?.cancel();
1474
+ heartbeatHandle = null;
1475
+ }
1476
+ };
1477
+ const launchDetect = () => {
1478
+ if (!abort) return;
1479
+ detectHandle?.cancel();
1480
+ detectHandle = startDetectEffect(env, dispatch, abort.signal, options.detect);
1481
+ };
1482
+ const launchNegotiate = () => {
1483
+ if (!abort) return;
1484
+ negotiateHandle?.cancel();
1485
+ negotiateHandle = startNegotiateEffect(
1486
+ env,
1487
+ dispatch,
1488
+ abort.signal,
1489
+ buildReadyPayload(options),
1490
+ options.negotiate
1491
+ );
1492
+ };
1493
+ const launchSubscriptions = () => {
1494
+ if (!abort) return;
1495
+ if (subscriptionsHandle) return;
1496
+ subscriptionsHandle = subscriptionsBinder({
1497
+ dispatch,
1498
+ getGeneration: () => snapshot.generation,
1499
+ onRecordPayload: (m) => mappingsHandle?.ingestStreamPayload("stream_record", m),
1500
+ onRecordsPayload: (m) => mappingsHandle?.ingestStreamPayload("stream_records", m),
1501
+ onNewRecordPayload: (m) => mappingsHandle?.ingestStreamPayload("stream_new_record", m)
1502
+ });
1503
+ };
1504
+ const launchMappings = () => {
1505
+ if (!abort) return;
1506
+ launchSubscriptions();
1507
+ if (mappingsHandle) return;
1508
+ mappingsHandle = startMappingsEffect(
1509
+ env,
1510
+ dispatch,
1511
+ abort.signal,
1512
+ declared,
1513
+ () => snapshot.generation,
1514
+ options.mappings
1515
+ );
1516
+ };
1517
+ const launchHeartbeat = () => {
1518
+ if (!abort) return;
1519
+ if (options.heartbeat === false) return;
1520
+ if (heartbeatHandle) return;
1521
+ heartbeatHandle = startHeartbeatEffect(
1522
+ env,
1523
+ dispatch,
1524
+ abort.signal,
1525
+ options.heartbeat ?? {}
1526
+ );
1527
+ };
1528
+ const cancelAllEffects = () => {
1529
+ detectHandle?.cancel();
1530
+ detectHandle = null;
1531
+ negotiateHandle?.cancel();
1532
+ negotiateHandle = null;
1533
+ mappingsHandle?.cancel();
1534
+ mappingsHandle = null;
1535
+ heartbeatHandle?.cancel();
1536
+ heartbeatHandle = null;
1537
+ if (abort && !abort.signal.aborted) abort.abort();
1538
+ };
1539
+ const controls = {
1540
+ start() {
1541
+ if (started) return;
1542
+ started = true;
1543
+ abort = new AbortController();
1544
+ launchDetect();
1545
+ },
1546
+ stop() {
1547
+ if (!started) return;
1548
+ started = false;
1549
+ cancelAllEffects();
1550
+ subscriptionsHandle?.cancel();
1551
+ subscriptionsHandle = null;
1552
+ snapshot = initialGristSnapshot();
1553
+ notify();
1554
+ },
1555
+ reload() {
1556
+ if (!started) {
1557
+ controls.start();
1558
+ return;
1559
+ }
1560
+ recheckAuthzFromCacheAfterOnline = true;
1561
+ try {
1562
+ options.onBeforeReload?.();
1563
+ } catch (err) {
1564
+ options.onError?.(err, "onBeforeReload");
1565
+ }
1566
+ cancelAllEffects();
1567
+ dispatch({ type: "BUMP_GENERATION", atMs: env.now(), reason: "reload" });
1568
+ snapshot = {
1569
+ ...initialGristSnapshot(),
1570
+ generation: nextGeneration(snapshot.generation)
1571
+ };
1572
+ ctx.resolver = null;
1573
+ abort = new AbortController();
1574
+ launchDetect();
1575
+ notify();
1576
+ },
1577
+ restart() {
1578
+ controls.reload();
1579
+ if (typeof window !== "undefined" && typeof window.location?.reload === "function") {
1580
+ try {
1581
+ window.location.reload();
1582
+ } catch (err) {
1583
+ options.onError?.(err, "restart");
1584
+ }
1585
+ }
1586
+ },
1587
+ subscribe(listener) {
1588
+ listeners.add(listener);
1589
+ return () => listeners.delete(listener);
1590
+ },
1591
+ getSnapshot: () => snapshot,
1592
+ dispatch,
1593
+ recordRpcSuccess() {
1594
+ heartbeatHandle?.recordRpcSuccess();
1595
+ },
1596
+ recordRpcFailure() {
1597
+ heartbeatHandle?.recordRpcFailure();
1598
+ }
1599
+ };
1600
+ return controls;
1601
+ }
1602
+ function buildReadyPayload(options) {
1603
+ const payload = {
1604
+ requiredAccess: options.requiredAccess ?? "read table",
1605
+ columns: options.columns ?? []
1606
+ };
1607
+ if (options.allowSelectBy !== void 0) payload.allowSelectBy = options.allowSelectBy;
1608
+ if (options.hasCustomOptions !== void 0) payload.hasCustomOptions = options.hasCustomOptions;
1609
+ if (options.onEditOptions) payload.onEditOptions = options.onEditOptions;
1610
+ return payload;
1611
+ }
1612
+
1613
+ // src/sdk/internal/embedded-handshake-manager.ts
1614
+ var embedded = null;
1615
+ function acquireEmbeddedHandshakeManager(options) {
1616
+ if (!embedded) {
1617
+ embedded = {
1618
+ manager: createGristHandshakeManager(options),
1619
+ refCount: 0
1620
+ };
1621
+ embedded.manager.start();
1622
+ }
1623
+ embedded.refCount += 1;
1624
+ return embedded.manager;
1625
+ }
1626
+ function releaseEmbeddedHandshakeManager() {
1627
+ if (!embedded) return;
1628
+ embedded.refCount -= 1;
1629
+ if (embedded.refCount <= 0) {
1630
+ embedded.manager.stop();
1631
+ embedded = null;
1632
+ }
1633
+ }
1634
+
1635
+ // src/sdk/internal/handshake-manager-context.ts
1636
+ var GristHandshakeManagerContext = (0, import_react.createContext)(null);
1637
+ function useGristManagerOptional() {
1638
+ return (0, import_react.useContext)(GristHandshakeManagerContext);
1639
+ }
1640
+ function useGristManager(options) {
1641
+ const fromProvider = (0, import_react.useContext)(GristHandshakeManagerContext);
1642
+ const optionsRef = (0, import_react.useRef)(options);
1643
+ optionsRef.current = options;
1644
+ const embeddedRef = (0, import_react.useRef)(null);
1645
+ const ownsEmbeddedRef = (0, import_react.useRef)(false);
1646
+ if (fromProvider) {
1647
+ return fromProvider;
1648
+ }
1649
+ if (embeddedRef.current === null) {
1650
+ embeddedRef.current = acquireEmbeddedHandshakeManager(
1651
+ buildManagerOptionsFromGristOptions(optionsRef.current)
1652
+ );
1653
+ ownsEmbeddedRef.current = true;
1654
+ }
1655
+ (0, import_react.useEffect)(() => {
1656
+ if (!ownsEmbeddedRef.current) return;
1657
+ return () => {
1658
+ releaseEmbeddedHandshakeManager();
1659
+ embeddedRef.current = null;
1660
+ ownsEmbeddedRef.current = false;
1661
+ };
1662
+ }, []);
1663
+ return embeddedRef.current;
1664
+ }
1665
+
1666
+ // src/sdk/internal/hooks/use-grist-core.ts
1667
+ function computeAvailabilityFromSnapshot(snapshot) {
1668
+ const { phase } = snapshot.lifecycle;
1669
+ if (phase === "idle" || phase === "detecting") return null;
1670
+ if (phase === "terminated") {
1671
+ const reason = snapshot.lifecycle.reason.kind;
1672
+ if (reason === "not_embedded" || reason === "script_timeout") return false;
1673
+ return true;
1674
+ }
1675
+ return true;
1676
+ }
1677
+ function useGristCore(options) {
1678
+ const manager = useGristManager(options);
1679
+ return useGristCoreFromManager(manager);
1680
+ }
1681
+ function useGristCoreFromManager(manager) {
1682
+ const snapshot = (0, import_react2.useSyncExternalStore)(
1683
+ manager.subscribe,
1684
+ manager.getSnapshot,
1685
+ initialGristSnapshot
1686
+ );
1687
+ const status = deriveStatus(snapshot);
1688
+ const error = deriveErrorMessage(snapshot);
1689
+ const docApi = (0, import_react2.useMemo)(() => {
1690
+ if (snapshot.lifecycle.phase !== "online") return null;
1691
+ if (typeof grist === "undefined") return null;
1692
+ return grist.docApi ?? null;
1693
+ }, [snapshot.lifecycle.phase, snapshot.generation]);
1694
+ const isAvailable = computeAvailabilityFromSnapshot(snapshot);
1695
+ const reload = (0, import_react2.useCallback)(async () => {
1696
+ manager.reload();
1697
+ }, [manager]);
1698
+ const capabilities = (0, import_react2.useMemo)(() => deriveCapabilities(snapshot), [snapshot]);
1699
+ return (0, import_react2.useMemo)(
1700
+ () => ({
1701
+ status,
1702
+ isAvailable,
1703
+ isReady: status === "ready",
1704
+ error,
1705
+ docApi,
1706
+ capabilities,
1707
+ reload
1708
+ }),
1709
+ [status, isAvailable, error, docApi, capabilities, reload]
1710
+ );
1711
+ }
1712
+
1713
+ // src/sdk/low-level-hooks/use-grist-availability.ts
1714
+ function useGristAvailability(options) {
1715
+ const { isAvailable } = useGristCore(options);
1716
+ return isAvailable;
1717
+ }
1718
+
1719
+ // src/sdk/low-level-hooks/use-grist-ready.ts
1720
+ function useGristReady(options) {
1721
+ const { isAvailable, docApi, error, reload } = useGristCore(options);
1722
+ return { isAvailable, docApi, error, reload };
1723
+ }
1724
+
1725
+ // src/sdk/low-level-hooks/use-grist-handshake.ts
1726
+ var import_react3 = require("react");
1727
+ function useGristHandshake(options = {}) {
1728
+ const optionsRef = (0, import_react3.useRef)(options);
1729
+ optionsRef.current = options;
1730
+ const managerRef = (0, import_react3.useRef)(null);
1731
+ if (managerRef.current === null) {
1732
+ managerRef.current = createGristHandshakeManager(options);
1733
+ }
1734
+ const manager = managerRef.current;
1735
+ (0, import_react3.useEffect)(() => {
1736
+ manager.start();
1737
+ return () => {
1738
+ manager.stop();
1739
+ };
1740
+ }, [manager]);
1741
+ const snapshot = (0, import_react3.useSyncExternalStore)(
1742
+ manager.subscribe,
1743
+ manager.getSnapshot,
1744
+ initialGristSnapshot
1745
+ );
1746
+ const projected = (0, import_react3.useMemo)(
1747
+ () => ({
1748
+ status: deriveStatus(snapshot),
1749
+ error: deriveErrorMessage(snapshot),
1750
+ capabilities: deriveCapabilities(snapshot)
1751
+ }),
1752
+ [snapshot]
1753
+ );
1754
+ return (0, import_react3.useMemo)(
1755
+ () => ({
1756
+ snapshot,
1757
+ status: projected.status,
1758
+ error: projected.error,
1759
+ capabilities: projected.capabilities,
1760
+ reload: manager.reload,
1761
+ restart: manager.restart
1762
+ }),
1763
+ [snapshot, projected, manager]
1764
+ );
1765
+ }
1766
+ function useGristCapabilities(options = {}) {
1767
+ return useGristHandshake(options).capabilities;
1768
+ }
1769
+
1770
+ // src/sdk/components/grist-handshake-provider.tsx
1771
+ var import_react4 = require("react");
1772
+ var import_jsx_runtime = require("react/jsx-runtime");
1773
+ var GristHandshakeReactContext = (0, import_react4.createContext)(null);
1774
+ function GristHandshakeProvider({ options, children }) {
1775
+ const managerRef = (0, import_react4.useRef)(null);
1776
+ if (managerRef.current === null) {
1777
+ managerRef.current = createGristHandshakeManager(options ?? {});
1778
+ }
1779
+ const manager = managerRef.current;
1780
+ (0, import_react4.useEffect)(() => {
1781
+ manager.start();
1782
+ return () => {
1783
+ manager.stop();
1784
+ };
1785
+ }, [manager]);
1786
+ const snapshot = (0, import_react4.useSyncExternalStore)(
1787
+ manager.subscribe,
1788
+ manager.getSnapshot,
1789
+ initialGristSnapshot
1790
+ );
1791
+ const value = (0, import_react4.useMemo)(
1792
+ () => ({
1793
+ snapshot,
1794
+ status: deriveStatus(snapshot),
1795
+ error: deriveErrorMessage(snapshot),
1796
+ capabilities: deriveCapabilities(snapshot),
1797
+ reload: manager.reload,
1798
+ restart: manager.restart,
1799
+ recordRpcSuccess: manager.recordRpcSuccess,
1800
+ recordRpcFailure: manager.recordRpcFailure
1801
+ }),
1802
+ [snapshot, manager]
1803
+ );
1804
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(GristHandshakeReactContext.Provider, { value, children });
1805
+ }
1806
+ function useGristHandshakeContext() {
1807
+ const ctx = (0, import_react4.useContext)(GristHandshakeReactContext);
1808
+ if (!ctx) {
1809
+ throw new Error(
1810
+ "useGristHandshakeContext() must be used inside <GristHandshakeProvider>"
1811
+ );
1812
+ }
1813
+ return ctx;
1814
+ }
1815
+ function useGristHandshakeContextOptional() {
1816
+ return (0, import_react4.useContext)(GristHandshakeReactContext);
1817
+ }
1818
+
1819
+ // src/sdk/low-level-hooks/use-grist-record.ts
1820
+ var import_react5 = require("react");
1821
+ function useGristRecord(cb, options) {
1822
+ const cbRef = (0, import_react5.useRef)(cb);
1823
+ (0, import_react5.useEffect)(() => {
1824
+ cbRef.current = cb;
1825
+ }, [cb]);
1826
+ const [mappings, setMappings] = (0, import_react5.useState)(null);
1827
+ const { docApi, error: readyError } = useGristReady({
1828
+ requiredAccess: options?.requiredAccess ?? "read table",
1829
+ columns: options?.columns,
1830
+ allowSelectBy: options?.allowSelectBy,
1831
+ hasCustomOptions: options?.hasCustomOptions,
1832
+ onEditOptions: options?.onEditOptions
1833
+ });
1834
+ (0, import_react5.useEffect)(() => {
1835
+ if (!docApi) return;
1836
+ return recordEvent.subscribe(({ record, mappings: nextMappings }) => {
1837
+ setMappings(nextMappings);
1838
+ cbRef.current(record, nextMappings);
1839
+ });
1840
+ }, [docApi]);
1841
+ return {
1842
+ loading: docApi === null && !readyError,
1843
+ error: readyError,
1844
+ mappings
1845
+ };
1846
+ }
1847
+
1848
+ // src/sdk/low-level-hooks/use-grist-records.ts
1849
+ var import_react6 = require("react");
1850
+ function useGristRecords(cb, options) {
1851
+ const cbRef = (0, import_react6.useRef)(cb);
1852
+ (0, import_react6.useEffect)(() => {
1853
+ cbRef.current = cb;
1854
+ }, [cb]);
1855
+ const [mappings, setMappings] = (0, import_react6.useState)(null);
1856
+ const { docApi, error: readyError } = useGristReady({
1857
+ requiredAccess: options?.requiredAccess ?? "read table",
1858
+ columns: options?.columns,
1859
+ allowSelectBy: options?.allowSelectBy,
1860
+ hasCustomOptions: options?.hasCustomOptions,
1861
+ onEditOptions: options?.onEditOptions
1862
+ });
1863
+ (0, import_react6.useEffect)(() => {
1864
+ if (!docApi) return;
1865
+ return recordsEvent.subscribe(({ records, mappings: nextMappings }) => {
1866
+ setMappings(nextMappings);
1867
+ cbRef.current(records, nextMappings);
1868
+ });
1869
+ }, [docApi]);
1870
+ return {
1871
+ loading: docApi === null && !readyError,
1872
+ error: readyError,
1873
+ mappings
1874
+ };
1875
+ }
1876
+
1877
+ // src/sdk/low-level-hooks/use-grist-new-record.ts
1878
+ var import_react7 = require("react");
1879
+ function useGristNewRecord(options) {
1880
+ const { docApi, error: readyError } = useGristReady({
1881
+ requiredAccess: options?.requiredAccess ?? "read table",
1882
+ columns: options?.columns,
1883
+ allowSelectBy: options?.allowSelectBy,
1884
+ hasCustomOptions: options?.hasCustomOptions,
1885
+ onEditOptions: options?.onEditOptions
1886
+ });
1887
+ const [isNewRecord, setIsNewRecord] = (0, import_react7.useState)(false);
1888
+ const [mappings, setMappings] = (0, import_react7.useState)(null);
1889
+ const subscribedRef = (0, import_react7.useRef)(false);
1890
+ (0, import_react7.useEffect)(() => {
1891
+ if (!docApi || subscribedRef.current) return;
1892
+ if (typeof grist.onNewRecord !== "function") return;
1893
+ subscribedRef.current = true;
1894
+ return newRecordEvent.subscribe(({ mappings: nextMappings }) => {
1895
+ setIsNewRecord(true);
1896
+ setMappings(nextMappings);
1897
+ });
1898
+ }, [docApi]);
1899
+ return {
1900
+ isNewRecord,
1901
+ mappings,
1902
+ loading: docApi === null && !readyError,
1903
+ error: readyError
1904
+ };
1905
+ }
1906
+
1907
+ // src/sdk/mid-level-hooks/use-grist-actions.ts
1908
+ var import_react9 = require("react");
1909
+
1910
+ // src/sdk/helpers/grist-user-actions.ts
1911
+ function gristUpdateRecordAction(tableId, rowId, patch) {
1912
+ return ["UpdateRecord", tableId, rowId, patch];
1913
+ }
1914
+ function gristAddRecordAction(tableId, values) {
1915
+ return ["AddRecord", tableId, null, values];
1916
+ }
1917
+ function gristRemoveRecordAction(tableId, rowId) {
1918
+ return ["RemoveRecord", tableId, rowId];
1919
+ }
1920
+ function gristBulkUpdateRecordAction(tableId, rowIds, columnarPatch) {
1921
+ return ["BulkUpdateRecord", tableId, rowIds, columnarPatch];
1922
+ }
1923
+ function gristBulkAddRecordAction(tableId, values, rowIds) {
1924
+ const length = inferBulkLength(values);
1925
+ const ids = rowIds ?? new Array(length).fill(null);
1926
+ return ["BulkAddRecord", tableId, ids, values];
1927
+ }
1928
+ function gristBulkRemoveRecordAction(tableId, rowIds) {
1929
+ return ["BulkRemoveRecord", tableId, rowIds];
1930
+ }
1931
+ function inferBulkLength(values) {
1932
+ for (const arr of Object.values(values)) if (Array.isArray(arr)) return arr.length;
1933
+ return 0;
1934
+ }
1935
+
1936
+ // src/sdk/internal/hooks/use-rpc-heartbeat-coalesce.ts
1937
+ var import_react8 = require("react");
1938
+ function useRpcHeartbeatCoalesce() {
1939
+ const manager = useGristManagerOptional();
1940
+ return (0, import_react8.useCallback)(
1941
+ async (fn) => {
1942
+ try {
1943
+ const result = await fn();
1944
+ manager?.recordRpcSuccess();
1945
+ return result;
1946
+ } catch (err) {
1947
+ throw err;
1948
+ }
1949
+ },
1950
+ [manager]
1951
+ );
1952
+ }
1953
+
1954
+ // src/sdk/mid-level-hooks/use-grist-actions.ts
1955
+ function useGristActions(options) {
1956
+ const requiredAccess = options?.requiredAccess ?? "full";
1957
+ const { docApi, error: readyError } = useGristReady({
1958
+ requiredAccess,
1959
+ columns: options?.columns,
1960
+ allowSelectBy: options?.allowSelectBy,
1961
+ hasCustomOptions: options?.hasCustomOptions,
1962
+ onEditOptions: options?.onEditOptions
1963
+ });
1964
+ const [status, setStatus] = (0, import_react9.useState)("idle");
1965
+ const [actionError, setActionError] = (0, import_react9.useState)(null);
1966
+ const coalesceRpc = useRpcHeartbeatCoalesce();
1967
+ const apply = (0, import_react9.useCallback)(
1968
+ async (actions, applyOptions) => {
1969
+ if (!docApi) throw new Error("Grist docApi is not ready");
1970
+ setStatus("running");
1971
+ setActionError(null);
1972
+ try {
1973
+ const out = await coalesceRpc(() => docApi.applyUserActions(actions, applyOptions));
1974
+ setStatus("idle");
1975
+ return out;
1976
+ } catch (err) {
1977
+ const message = err instanceof Error ? err.message : String(err);
1978
+ setActionError(message);
1979
+ setStatus("error");
1980
+ throw err;
1981
+ }
1982
+ },
1983
+ [docApi, coalesceRpc]
1984
+ );
1985
+ const updateRecord = (0, import_react9.useCallback)(
1986
+ (tableId, recordId, patch, applyOptions) => apply([gristUpdateRecordAction(tableId, recordId, patch)], applyOptions),
1987
+ [apply]
1988
+ );
1989
+ const addRecord = (0, import_react9.useCallback)(
1990
+ (tableId, values, applyOptions) => apply([gristAddRecordAction(tableId, values)], applyOptions),
1991
+ [apply]
1992
+ );
1993
+ const removeRecord = (0, import_react9.useCallback)(
1994
+ (tableId, recordId, applyOptions) => apply([gristRemoveRecordAction(tableId, recordId)], applyOptions),
1995
+ [apply]
1996
+ );
1997
+ const bulkAddRecord = (0, import_react9.useCallback)(
1998
+ (tableId, values, applyOptions) => apply([gristBulkAddRecordAction(tableId, values)], applyOptions),
1999
+ [apply]
2000
+ );
2001
+ const bulkUpdateRecord = (0, import_react9.useCallback)(
2002
+ (tableId, rowIds, columnarPatch, applyOptions) => apply([gristBulkUpdateRecordAction(tableId, rowIds, columnarPatch)], applyOptions),
2003
+ [apply]
2004
+ );
2005
+ const bulkRemoveRecord = (0, import_react9.useCallback)(
2006
+ (tableId, rowIds, applyOptions) => apply([gristBulkRemoveRecordAction(tableId, rowIds)], applyOptions),
2007
+ [apply]
2008
+ );
2009
+ return {
2010
+ status: readyError ? "error" : status,
2011
+ error: readyError ?? actionError,
2012
+ apply,
2013
+ updateRecord,
2014
+ addRecord,
2015
+ removeRecord,
2016
+ bulkAddRecord,
2017
+ bulkUpdateRecord,
2018
+ bulkRemoveRecord
2019
+ };
2020
+ }
2021
+
2022
+ // src/sdk/mid-level-hooks/use-grist-mapped-record.ts
2023
+ var import_react10 = require("react");
2024
+ function manualMapBack(patch, mappings) {
2025
+ if (!mappings) return { ...patch };
2026
+ const out = {};
2027
+ for (const [name, value] of Object.entries(patch)) {
2028
+ const target = mappings[name];
2029
+ if (Array.isArray(target)) {
2030
+ if (typeof console !== "undefined") {
2031
+ console.warn(`[lib/grist] mapBack: cannot reverse-map allowMultiple field "${name}" without grist.mapColumnNamesBack`);
2032
+ }
2033
+ continue;
2034
+ }
2035
+ out[target ?? name] = value;
2036
+ }
2037
+ return out;
2038
+ }
2039
+ function useGristMappedRecord(options) {
2040
+ const requiredAccess = options?.requiredAccess ?? "read table";
2041
+ const { docApi, error: readyError } = useGristReady({
2042
+ requiredAccess,
2043
+ columns: options?.columns,
2044
+ allowSelectBy: options?.allowSelectBy,
2045
+ hasCustomOptions: options?.hasCustomOptions,
2046
+ onEditOptions: options?.onEditOptions
2047
+ });
2048
+ const [rawRecord, setRawRecord] = (0, import_react10.useState)(null);
2049
+ const [mappedRecord, setMappedRecord] = (0, import_react10.useState)(null);
2050
+ const [mappings, setMappings] = (0, import_react10.useState)(null);
2051
+ (0, import_react10.useEffect)(() => {
2052
+ if (!docApi) return;
2053
+ return recordEvent.subscribe(({ record, mappings: nextMappings }) => {
2054
+ setRawRecord(record);
2055
+ setMappings(nextMappings);
2056
+ if (!record) {
2057
+ setMappedRecord(null);
2058
+ return;
2059
+ }
2060
+ if (typeof grist.mapColumnNames === "function") {
2061
+ const mapped = grist.mapColumnNames(record);
2062
+ setMappedRecord(
2063
+ mapped !== null && mapped !== void 0 ? mapped : null
2064
+ );
2065
+ return;
2066
+ }
2067
+ setMappedRecord(record);
2068
+ });
2069
+ }, [docApi]);
2070
+ const mapBack = (0, import_react10.useCallback)(
2071
+ (patch) => {
2072
+ if (typeof grist.mapColumnNamesBack === "function") {
2073
+ return grist.mapColumnNamesBack(patch);
2074
+ }
2075
+ return manualMapBack(patch, mappings);
2076
+ },
2077
+ [mappings]
2078
+ );
2079
+ const resolveColumnId = (0, import_react10.useCallback)(
2080
+ (logicalName) => {
2081
+ const value = mappings?.[logicalName];
2082
+ if (Array.isArray(value)) return void 0;
2083
+ return value ?? void 0;
2084
+ },
2085
+ [mappings]
2086
+ );
2087
+ return {
2088
+ rawRecord,
2089
+ mappedRecord,
2090
+ mappings,
2091
+ loading: docApi === null && !readyError,
2092
+ error: readyError,
2093
+ mapBack,
2094
+ resolveColumnId
2095
+ };
2096
+ }
2097
+
2098
+ // src/sdk/mid-level-hooks/use-grist-table-ops.ts
2099
+ var import_react11 = require("react");
2100
+ function resolveOps(tableId) {
2101
+ if (tableId === "selected") {
2102
+ if (!grist.selectedTable) throw new Error("grist.selectedTable is not available");
2103
+ return grist.selectedTable;
2104
+ }
2105
+ if (typeof grist.getTable !== "function") {
2106
+ throw new Error("grist.getTable is not available in this Grist version");
2107
+ }
2108
+ return grist.getTable(tableId);
2109
+ }
2110
+ function useGristTableOps(options) {
2111
+ const requiredAccess = options?.requiredAccess ?? "full";
2112
+ const tableIdOption = options?.tableId ?? "selected";
2113
+ const { docApi, error: readyError } = useGristReady({
2114
+ requiredAccess,
2115
+ columns: options?.columns,
2116
+ allowSelectBy: options?.allowSelectBy,
2117
+ hasCustomOptions: options?.hasCustomOptions,
2118
+ onEditOptions: options?.onEditOptions
2119
+ });
2120
+ const [status, setStatus] = (0, import_react11.useState)("idle");
2121
+ const [actionError, setActionError] = (0, import_react11.useState)(null);
2122
+ const coalesceRpc = useRpcHeartbeatCoalesce();
2123
+ let ops = null;
2124
+ let resolveError = null;
2125
+ if (docApi) {
2126
+ try {
2127
+ ops = resolveOps(tableIdOption);
2128
+ } catch (err) {
2129
+ resolveError = err instanceof Error ? err.message : String(err);
2130
+ }
2131
+ }
2132
+ const wrap = (0, import_react11.useCallback)(
2133
+ async (run) => {
2134
+ if (!ops) throw new Error("Grist table operations are not ready");
2135
+ setStatus("running");
2136
+ setActionError(null);
2137
+ try {
2138
+ const out = await coalesceRpc(() => run(ops));
2139
+ setStatus("idle");
2140
+ return out;
2141
+ } catch (err) {
2142
+ const message = err instanceof Error ? err.message : String(err);
2143
+ setActionError(message);
2144
+ setStatus("error");
2145
+ throw err;
2146
+ }
2147
+ },
2148
+ [ops, coalesceRpc]
2149
+ );
2150
+ const getTableId = (0, import_react11.useCallback)(async () => {
2151
+ if (!ops) throw new Error("Grist table operations are not ready");
2152
+ return ops.getTableId();
2153
+ }, [ops]);
2154
+ const create = (0, import_react11.useCallback)(
2155
+ (records, opOptions) => wrap((o) => o.create(records, opOptions)),
2156
+ [wrap]
2157
+ );
2158
+ const update = (0, import_react11.useCallback)(
2159
+ (records, opOptions) => wrap((o) => o.update(records, opOptions)),
2160
+ [wrap]
2161
+ );
2162
+ const upsert = (0, import_react11.useCallback)(
2163
+ (records, opOptions) => wrap((o) => o.upsert(records, opOptions)),
2164
+ [wrap]
2165
+ );
2166
+ const destroy = (0, import_react11.useCallback)(
2167
+ (recordIds) => wrap((o) => o.destroy(recordIds)),
2168
+ [wrap]
2169
+ );
2170
+ return {
2171
+ status: readyError || resolveError ? "error" : status,
2172
+ error: readyError ?? resolveError ?? actionError,
2173
+ getTableId,
2174
+ create,
2175
+ update,
2176
+ upsert,
2177
+ destroy
2178
+ };
2179
+ }
2180
+
2181
+ // src/sdk/mid-level-hooks/use-grist-rows-from-table.ts
2182
+ var import_react13 = require("react");
2183
+
2184
+ // src/sdk/helpers/grist-table-data.ts
2185
+ function tableDataToRows(data) {
2186
+ const idCol = data.id;
2187
+ if (!Array.isArray(idCol) || idCol.length === 0) return [];
2188
+ const keys = Object.keys(data);
2189
+ const n = idCol.length;
2190
+ const rows = [];
2191
+ for (let i = 0; i < n; i++) {
2192
+ const row = {};
2193
+ for (const k of keys) {
2194
+ const col = data[k];
2195
+ row[k] = Array.isArray(col) ? col[i] : void 0;
2196
+ }
2197
+ rows.push(row);
2198
+ }
2199
+ return rows;
2200
+ }
2201
+
2202
+ // src/sdk/internal/contexts.tsx
2203
+ var import_react12 = require("react");
2204
+ var GristCoreContext = (0, import_react12.createContext)(null);
2205
+ var GristSelectionContext = (0, import_react12.createContext)(null);
2206
+ var GristCurrentTableContext = (0, import_react12.createContext)(null);
2207
+ var GristWritesContext = (0, import_react12.createContext)(null);
2208
+ var GristReadsContext = (0, import_react12.createContext)(null);
2209
+ var GristWidgetOptionsApiContext = (0, import_react12.createContext)(null);
2210
+ var GristLinkingContext = (0, import_react12.createContext)(null);
2211
+ var GristAttachmentsRestContext = (0, import_react12.createContext)(null);
2212
+ var GristThemeContext = (0, import_react12.createContext)(null);
2213
+ var GristSectionApiContext = (0, import_react12.createContext)(null);
2214
+ function useRequiredContext(ctx, name) {
2215
+ const value = (0, import_react12.useContext)(ctx);
2216
+ if (!value) {
2217
+ throw new Error(`${name} must be used inside <GristWidgetProvider>`);
2218
+ }
2219
+ return value;
2220
+ }
2221
+ function useGristSelectionContext() {
2222
+ return useRequiredContext(GristSelectionContext, "useGristSelectionContext()");
2223
+ }
2224
+ function useGristWidgetOptionsApiContext() {
2225
+ return useRequiredContext(GristWidgetOptionsApiContext, "useGristWidgetOptionsApiContext()");
2226
+ }
2227
+
2228
+ // src/sdk/mid-level-hooks/use-grist-rows-from-table.ts
2229
+ function useGristRowsFromTable(options) {
2230
+ const requiredAccess = options.requiredAccess ?? "read table";
2231
+ const { docApi, error: readyError } = useGristReady({
2232
+ requiredAccess,
2233
+ columns: options.columns,
2234
+ allowSelectBy: options.allowSelectBy,
2235
+ hasCustomOptions: options.hasCustomOptions,
2236
+ onEditOptions: options.onEditOptions
2237
+ });
2238
+ const providerFetchTable = (0, import_react13.useContext)(GristReadsContext)?.fetchTable;
2239
+ const [rows, setRows] = (0, import_react13.useState)(null);
2240
+ const [loading, setLoading] = (0, import_react13.useState)(false);
2241
+ const [fetchError, setFetchError] = (0, import_react13.useState)(null);
2242
+ const transformRef = (0, import_react13.useRef)(options.transform);
2243
+ transformRef.current = options.transform;
2244
+ const coalesceRpc = useRpcHeartbeatCoalesce();
2245
+ const refresh = (0, import_react13.useCallback)(async () => {
2246
+ if (!docApi) return;
2247
+ setLoading(true);
2248
+ setFetchError(null);
2249
+ try {
2250
+ const data = providerFetchTable ? await providerFetchTable(options.tableId) : await coalesceRpc(
2251
+ () => docApi.fetchTable(options.tableId)
2252
+ );
2253
+ const raw = tableDataToRows(data);
2254
+ const t = transformRef.current;
2255
+ setRows(t ? raw.map((r) => t(r)) : raw);
2256
+ } catch (err) {
2257
+ setFetchError(err instanceof Error ? err.message : String(err));
2258
+ setRows(null);
2259
+ } finally {
2260
+ setLoading(false);
2261
+ }
2262
+ }, [docApi, providerFetchTable, options.tableId, coalesceRpc]);
2263
+ (0, import_react13.useEffect)(() => {
2264
+ if (docApi) void refresh();
2265
+ }, [docApi, refresh]);
2266
+ (0, import_react13.useEffect)(() => {
2267
+ if (!docApi || !options.pollIntervalMs || options.pollIntervalMs <= 0) return;
2268
+ const id = window.setInterval(() => void refresh(), options.pollIntervalMs);
2269
+ return () => window.clearInterval(id);
2270
+ }, [docApi, options.pollIntervalMs, refresh]);
2271
+ return {
2272
+ rows,
2273
+ loading,
2274
+ error: readyError ?? fetchError,
2275
+ refresh
2276
+ };
2277
+ }
2278
+
2279
+ // src/sdk/mid-level-hooks/use-grist-access-token.ts
2280
+ var import_react14 = require("react");
2281
+
2282
+ // src/sdk/helpers/grist-fetch-with-auth.ts
2283
+ var TOKEN_TTL_MS = 45e3;
2284
+ var cache = /* @__PURE__ */ new Map();
2285
+ var inFlight2 = /* @__PURE__ */ new Map();
2286
+ function cacheKey(readOnly) {
2287
+ return readOnly ? "ro" : "rw";
2288
+ }
2289
+ async function getGristAccessToken(docApi, options) {
2290
+ if (!docApi.getAccessToken) {
2291
+ throw new Error("getAccessToken is not available on docApi (need higher access level)");
2292
+ }
2293
+ const readOnly = options?.readOnly ?? false;
2294
+ const key = cacheKey(readOnly);
2295
+ const now = Date.now();
2296
+ const hit = cache.get(key);
2297
+ if (hit && now - hit.fetchedAt < TOKEN_TTL_MS) {
2298
+ return hit.token;
2299
+ }
2300
+ const pending = inFlight2.get(key);
2301
+ if (pending) return pending;
2302
+ const next = docApi.getAccessToken({ readOnly }).then((token) => {
2303
+ cache.set(key, { token, fetchedAt: Date.now() });
2304
+ inFlight2.delete(key);
2305
+ return token;
2306
+ });
2307
+ inFlight2.set(key, next);
2308
+ return next;
2309
+ }
2310
+ function clearGristAccessTokenCache() {
2311
+ cache.clear();
2312
+ inFlight2.clear();
2313
+ }
2314
+ async function fetchWithGristAuth(docApi, path, init) {
2315
+ const readOnly = init?.readOnly ?? false;
2316
+ let token;
2317
+ try {
2318
+ token = await getGristAccessToken(docApi, { readOnly });
2319
+ } catch (err) {
2320
+ clearGristAccessTokenCache();
2321
+ throw err;
2322
+ }
2323
+ const isAbsolute = /^https?:\/\//i.test(path);
2324
+ const cleanPath = isAbsolute ? path : path.startsWith("/") ? path : `/${path}`;
2325
+ const method = (init?.method ?? "GET").toUpperCase();
2326
+ const url = isAbsolute ? new URL(path) : new URL(`${token.baseUrl.replace(/\/$/, "")}${cleanPath}`);
2327
+ if (!url.searchParams.has("auth")) url.searchParams.set("auth", token.token);
2328
+ const headers = new Headers(init?.headers ?? {});
2329
+ headers.delete("Authorization");
2330
+ const response = await fetch(url.toString(), { ...init, headers });
2331
+ if (response.status === 401) {
2332
+ clearGristAccessTokenCache();
2333
+ const retryToken = await getGristAccessToken(docApi, { readOnly });
2334
+ url.searchParams.set("auth", retryToken.token);
2335
+ return fetch(url.toString(), { ...init, headers });
2336
+ }
2337
+ return response;
2338
+ }
2339
+
2340
+ // src/sdk/mid-level-hooks/use-grist-access-token.ts
2341
+ function useGristAccessToken(options) {
2342
+ const requiredAccess = options?.requiredAccess ?? "full";
2343
+ const readOnlyDefault = options?.readOnly ?? false;
2344
+ const prefetch = options?.prefetch ?? false;
2345
+ const { docApi, error: readyError } = useGristReady({
2346
+ requiredAccess,
2347
+ columns: options?.columns,
2348
+ allowSelectBy: options?.allowSelectBy,
2349
+ hasCustomOptions: options?.hasCustomOptions,
2350
+ onEditOptions: options?.onEditOptions
2351
+ });
2352
+ const [token, setToken] = (0, import_react14.useState)(null);
2353
+ const [loading, setLoading] = (0, import_react14.useState)(false);
2354
+ const [error, setError] = (0, import_react14.useState)(null);
2355
+ const refresh = (0, import_react14.useCallback)(
2356
+ async (overrides) => {
2357
+ if (!docApi) throw new Error("Grist is not ready");
2358
+ setLoading(true);
2359
+ setError(null);
2360
+ try {
2361
+ const next = await getGristAccessToken(docApi, { readOnly: overrides?.readOnly ?? readOnlyDefault });
2362
+ setToken(next);
2363
+ return next;
2364
+ } catch (err) {
2365
+ const message = err instanceof Error ? err.message : String(err);
2366
+ setError(message);
2367
+ throw err;
2368
+ } finally {
2369
+ setLoading(false);
2370
+ }
2371
+ },
2372
+ [docApi, readOnlyDefault]
2373
+ );
2374
+ const fetchFn = (0, import_react14.useCallback)(
2375
+ (path, init) => {
2376
+ if (!docApi) throw new Error("Grist is not ready");
2377
+ return fetchWithGristAuth(docApi, path, { readOnly: readOnlyDefault, ...init });
2378
+ },
2379
+ [docApi, readOnlyDefault]
2380
+ );
2381
+ (0, import_react14.useEffect)(() => {
2382
+ if (docApi && prefetch) void refresh();
2383
+ }, [docApi, prefetch, refresh]);
2384
+ return {
2385
+ token,
2386
+ loading,
2387
+ error: readyError ?? error,
2388
+ refresh,
2389
+ fetch: fetchFn
2390
+ };
2391
+ }
2392
+
2393
+ // src/sdk/mid-level-hooks/use-grist-section.ts
2394
+ var import_react15 = require("react");
2395
+ function useGristSection(options) {
2396
+ const { docApi, error: readyError } = useGristReady({
2397
+ requiredAccess: options?.requiredAccess ?? "read table",
2398
+ columns: options?.columns,
2399
+ allowSelectBy: options?.allowSelectBy,
2400
+ hasCustomOptions: options?.hasCustomOptions,
2401
+ onEditOptions: options?.onEditOptions
2402
+ });
2403
+ const [mappings, setMappings] = (0, import_react15.useState)(null);
2404
+ const [loading, setLoading] = (0, import_react15.useState)(false);
2405
+ const [error, setError] = (0, import_react15.useState)(null);
2406
+ const refresh = (0, import_react15.useCallback)(async () => {
2407
+ if (!docApi) return;
2408
+ if (!grist.sectionApi?.mappings) {
2409
+ setError("grist.sectionApi.mappings is not available in this Grist version");
2410
+ return;
2411
+ }
2412
+ setLoading(true);
2413
+ setError(null);
2414
+ try {
2415
+ const next = await grist.sectionApi.mappings();
2416
+ setMappings(next);
2417
+ } catch (err) {
2418
+ setError(err instanceof Error ? err.message : String(err));
2419
+ } finally {
2420
+ setLoading(false);
2421
+ }
2422
+ }, [docApi]);
2423
+ const configure = (0, import_react15.useCallback)(async (next) => {
2424
+ if (!grist.sectionApi?.configure) {
2425
+ throw new Error("grist.sectionApi.configure is not available in this Grist version");
2426
+ }
2427
+ await grist.sectionApi.configure(next);
2428
+ }, []);
2429
+ (0, import_react15.useEffect)(() => {
2430
+ if (docApi) void refresh();
2431
+ }, [docApi, refresh]);
2432
+ return {
2433
+ mappings,
2434
+ loading,
2435
+ error: readyError ?? error,
2436
+ refresh,
2437
+ configure
2438
+ };
2439
+ }
2440
+
2441
+ // src/sdk/mid-level-hooks/use-grist-widget-options.ts
2442
+ var import_react16 = require("react");
2443
+ function mergeWithDefaults(defaults, stored, namespace) {
2444
+ if (stored === null || stored === void 0) return { ...defaults };
2445
+ const source = namespace ? stored[namespace] : stored;
2446
+ if (!source || typeof source !== "object") return { ...defaults };
2447
+ return { ...defaults, ...source };
2448
+ }
2449
+ function useGristWidgetOptions(config) {
2450
+ const requiredAccess = config.requiredAccess ?? "read table";
2451
+ const debounceMs = config.debounceMs ?? 250;
2452
+ const hasCustomOptions = config.hasCustomOptions ?? true;
2453
+ const { docApi, error: readyError } = useGristReady({
2454
+ requiredAccess,
2455
+ columns: config.columns,
2456
+ allowSelectBy: config.allowSelectBy,
2457
+ hasCustomOptions,
2458
+ onEditOptions: config.onEditOptions
2459
+ });
2460
+ const defaultsRef = (0, import_react16.useRef)(config.defaults);
2461
+ (0, import_react16.useEffect)(() => {
2462
+ defaultsRef.current = config.defaults;
2463
+ }, [config.defaults]);
2464
+ const [options, setOptionsState] = (0, import_react16.useState)(() => ({ ...config.defaults }));
2465
+ const [loading, setLoading] = (0, import_react16.useState)(true);
2466
+ const [error, setError] = (0, import_react16.useState)(null);
2467
+ const lastWrittenRef = (0, import_react16.useRef)(null);
2468
+ const debounceRef = (0, import_react16.useRef)(null);
2469
+ (0, import_react16.useEffect)(() => {
2470
+ if (!docApi) return;
2471
+ return optionsEvent.subscribe(({ options: stored }) => {
2472
+ const merged = mergeWithDefaults(defaultsRef.current, stored, config.namespace);
2473
+ lastWrittenRef.current = merged;
2474
+ setOptionsState(merged);
2475
+ setLoading(false);
2476
+ });
2477
+ }, [docApi, config.namespace]);
2478
+ const flushWrite = (0, import_react16.useCallback)(
2479
+ async (value) => {
2480
+ try {
2481
+ if (config.namespace) {
2482
+ await grist.setOption(config.namespace, value);
2483
+ } else {
2484
+ await grist.setOptions({ ...value });
2485
+ }
2486
+ lastWrittenRef.current = value;
2487
+ } catch (err) {
2488
+ setError(err instanceof Error ? err.message : String(err));
2489
+ }
2490
+ },
2491
+ [config.namespace]
2492
+ );
2493
+ const scheduleWrite = (0, import_react16.useCallback)(
2494
+ (value) => {
2495
+ if (debounceRef.current) window.clearTimeout(debounceRef.current);
2496
+ debounceRef.current = window.setTimeout(() => {
2497
+ debounceRef.current = null;
2498
+ void flushWrite(value);
2499
+ }, debounceMs);
2500
+ },
2501
+ [debounceMs, flushWrite]
2502
+ );
2503
+ (0, import_react16.useEffect)(() => {
2504
+ return () => {
2505
+ if (debounceRef.current) window.clearTimeout(debounceRef.current);
2506
+ };
2507
+ }, []);
2508
+ const setOptionsApi = (0, import_react16.useCallback)(
2509
+ (next) => {
2510
+ setOptionsState(next);
2511
+ scheduleWrite(next);
2512
+ },
2513
+ [scheduleWrite]
2514
+ );
2515
+ const patchOptionsApi = (0, import_react16.useCallback)(
2516
+ (patch) => {
2517
+ setOptionsState((prev) => {
2518
+ const next = { ...prev, ...patch };
2519
+ scheduleWrite(next);
2520
+ return next;
2521
+ });
2522
+ },
2523
+ [scheduleWrite]
2524
+ );
2525
+ const reset = (0, import_react16.useCallback)(async () => {
2526
+ if (debounceRef.current) {
2527
+ window.clearTimeout(debounceRef.current);
2528
+ debounceRef.current = null;
2529
+ }
2530
+ const next = { ...defaultsRef.current };
2531
+ setOptionsState(next);
2532
+ await flushWrite(next);
2533
+ }, [flushWrite]);
2534
+ return (0, import_react16.useMemo)(
2535
+ () => ({
2536
+ options,
2537
+ loading,
2538
+ error: readyError ?? error,
2539
+ setOptions: setOptionsApi,
2540
+ patchOptions: patchOptionsApi,
2541
+ reset
2542
+ }),
2543
+ [options, loading, readyError, error, setOptionsApi, patchOptionsApi, reset]
2544
+ );
2545
+ }
2546
+
2547
+ // src/sdk/mid-level-hooks/use-grist-widget-options-from-context.ts
2548
+ var import_react17 = require("react");
2549
+ function mergeWithDefaults2(defaults, stored, namespace) {
2550
+ if (stored === null || stored === void 0) return { ...defaults };
2551
+ const source = namespace ? stored[namespace] : stored;
2552
+ if (!source || typeof source !== "object") return { ...defaults };
2553
+ return { ...defaults, ...source };
2554
+ }
2555
+ function useGristWidgetOptionsFromContext(config) {
2556
+ const debounceMs = config.debounceMs ?? 250;
2557
+ const selection = useGristSelectionContext();
2558
+ const optionsApi = useGristWidgetOptionsApiContext();
2559
+ const defaultsRef = (0, import_react17.useRef)(config.defaults);
2560
+ (0, import_react17.useEffect)(() => {
2561
+ defaultsRef.current = config.defaults;
2562
+ }, [config.defaults]);
2563
+ const rawOptions = selection.widgetOptions;
2564
+ const hasReceived = rawOptions !== null;
2565
+ const merged = (0, import_react17.useMemo)(
2566
+ () => mergeWithDefaults2(defaultsRef.current, rawOptions, config.namespace),
2567
+ [rawOptions, config.namespace]
2568
+ );
2569
+ const [localOverride, setLocalOverride] = (0, import_react17.useState)(null);
2570
+ const options = localOverride ?? merged;
2571
+ (0, import_react17.useEffect)(() => {
2572
+ setLocalOverride(null);
2573
+ }, [rawOptions]);
2574
+ const debounceRef = (0, import_react17.useRef)(null);
2575
+ const flushWrite = (0, import_react17.useCallback)(
2576
+ async (value) => {
2577
+ if (config.namespace) {
2578
+ await optionsApi.setWidgetOption(config.namespace, value);
2579
+ } else {
2580
+ await optionsApi.setWidgetOptions({ ...value });
2581
+ }
2582
+ },
2583
+ [config.namespace, optionsApi]
2584
+ );
2585
+ const scheduleWrite = (0, import_react17.useCallback)(
2586
+ (value) => {
2587
+ if (debounceRef.current) window.clearTimeout(debounceRef.current);
2588
+ debounceRef.current = window.setTimeout(() => {
2589
+ debounceRef.current = null;
2590
+ void flushWrite(value);
2591
+ }, debounceMs);
2592
+ },
2593
+ [debounceMs, flushWrite]
2594
+ );
2595
+ (0, import_react17.useEffect)(() => {
2596
+ return () => {
2597
+ if (debounceRef.current) window.clearTimeout(debounceRef.current);
2598
+ };
2599
+ }, []);
2600
+ const setOptions = (0, import_react17.useCallback)(
2601
+ (next) => {
2602
+ setLocalOverride(next);
2603
+ scheduleWrite(next);
2604
+ },
2605
+ [scheduleWrite]
2606
+ );
2607
+ const patchOptions = (0, import_react17.useCallback)(
2608
+ (patch) => {
2609
+ setLocalOverride((prev) => {
2610
+ const base = prev ?? merged;
2611
+ const next = { ...base, ...patch };
2612
+ scheduleWrite(next);
2613
+ return next;
2614
+ });
2615
+ },
2616
+ [merged, scheduleWrite]
2617
+ );
2618
+ const reset = (0, import_react17.useCallback)(async () => {
2619
+ if (debounceRef.current) {
2620
+ window.clearTimeout(debounceRef.current);
2621
+ debounceRef.current = null;
2622
+ }
2623
+ const next = { ...defaultsRef.current };
2624
+ setLocalOverride(null);
2625
+ await flushWrite(next);
2626
+ }, [flushWrite]);
2627
+ return (0, import_react17.useMemo)(
2628
+ () => ({
2629
+ options,
2630
+ loading: !hasReceived,
2631
+ setOptions,
2632
+ patchOptions,
2633
+ reset
2634
+ }),
2635
+ [options, hasReceived, setOptions, patchOptions, reset]
2636
+ );
2637
+ }
2638
+
2639
+ // src/sdk/use-grist-table.ts
2640
+ var import_react18 = require("react");
2641
+ function isCurrentMode(option) {
2642
+ return option === void 0 || option === "current";
2643
+ }
2644
+ function useGristTable(options) {
2645
+ const requiredAccess = options?.requiredAccess ?? "read table";
2646
+ const tableIdOption = options?.tableId ?? "current";
2647
+ const { docApi, error: readyError } = useGristReady({
2648
+ requiredAccess,
2649
+ columns: options?.columns,
2650
+ allowSelectBy: options?.allowSelectBy,
2651
+ hasCustomOptions: options?.hasCustomOptions,
2652
+ onEditOptions: options?.onEditOptions
2653
+ });
2654
+ const [tableId, setTableId] = (0, import_react18.useState)(null);
2655
+ const [loading, setLoading] = (0, import_react18.useState)(false);
2656
+ const [error, setError] = (0, import_react18.useState)(null);
2657
+ const fetchTable = (0, import_react18.useCallback)(
2658
+ async (targetTableId) => {
2659
+ if (!docApi) throw new Error("Grist is not ready");
2660
+ return docApi.fetchTable(targetTableId);
2661
+ },
2662
+ [docApi]
2663
+ );
2664
+ const listTables = (0, import_react18.useCallback)(async () => {
2665
+ if (!docApi) throw new Error("Grist is not ready");
2666
+ const out = await Promise.resolve(docApi.listTables());
2667
+ return [...out];
2668
+ }, [docApi]);
2669
+ const getDocName = (0, import_react18.useCallback)(async () => {
2670
+ if (!docApi) throw new Error("Grist is not ready");
2671
+ return String(await Promise.resolve(docApi.getDocName()));
2672
+ }, [docApi]);
2673
+ const fetchSelectedTable = (0, import_react18.useCallback)(
2674
+ async (fetchOptions) => {
2675
+ if (!docApi) throw new Error("Grist is not ready");
2676
+ const impl = docApi.fetchSelectedTable ?? grist.fetchSelectedTable;
2677
+ if (!impl) throw new Error("fetchSelectedTable is not available in this Grist version");
2678
+ const merged = { keepEncoded: false, format: "rows", ...fetchOptions };
2679
+ return await impl(merged);
2680
+ },
2681
+ [docApi]
2682
+ );
2683
+ const fetchSelectedRecord = (0, import_react18.useCallback)(
2684
+ async (rowId, fetchOptions) => {
2685
+ if (!docApi) throw new Error("Grist is not ready");
2686
+ const impl = docApi.fetchSelectedRecord ?? grist.fetchSelectedRecord;
2687
+ if (!impl) throw new Error("fetchSelectedRecord is not available in this Grist version");
2688
+ const merged = { keepEncoded: false, format: "rows", ...fetchOptions };
2689
+ return await impl(rowId, merged);
2690
+ },
2691
+ [docApi]
2692
+ );
2693
+ const refresh = (0, import_react18.useCallback)(async () => {
2694
+ if (!docApi) return;
2695
+ if (!isCurrentMode(tableIdOption)) {
2696
+ setTableId(tableIdOption);
2697
+ setError(null);
2698
+ return;
2699
+ }
2700
+ setLoading(true);
2701
+ setError(null);
2702
+ try {
2703
+ const next = await grist.selectedTable?.getTableId();
2704
+ setTableId(next ?? null);
2705
+ } catch (err) {
2706
+ setTableId(null);
2707
+ setError(err instanceof Error ? err.message : String(err));
2708
+ } finally {
2709
+ setLoading(false);
2710
+ }
2711
+ }, [docApi, tableIdOption]);
2712
+ (0, import_react18.useEffect)(() => {
2713
+ if (docApi) void refresh();
2714
+ }, [docApi, refresh]);
2715
+ return {
2716
+ tableId,
2717
+ loading,
2718
+ error: readyError ?? error,
2719
+ refresh,
2720
+ fetchTable,
2721
+ listTables,
2722
+ getDocName,
2723
+ fetchSelectedTable,
2724
+ fetchSelectedRecord
2725
+ };
2726
+ }
2727
+ // Annotate the CommonJS export names for ESM import in node:
2728
+ 0 && (module.exports = {
2729
+ GristHandshakeProvider,
2730
+ useGristAccessToken,
2731
+ useGristActions,
2732
+ useGristAvailability,
2733
+ useGristCapabilities,
2734
+ useGristHandshake,
2735
+ useGristHandshakeContext,
2736
+ useGristHandshakeContextOptional,
2737
+ useGristMappedRecord,
2738
+ useGristNewRecord,
2739
+ useGristReady,
2740
+ useGristRecord,
2741
+ useGristRecords,
2742
+ useGristRowsFromTable,
2743
+ useGristSection,
2744
+ useGristTable,
2745
+ useGristTableOps,
2746
+ useGristWidgetOptions,
2747
+ useGristWidgetOptionsFromContext
2748
+ });
2749
+ //# sourceMappingURL=advanced.cjs.map