@carlonicora/nextjs-jsonapi 6.22.0 → 6.23.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 (175) hide show
  1. package/dist/{BlockNoteEditor-HW3TK7SM.js → BlockNoteEditor-PPRML5CO.js} +23 -23
  2. package/dist/{BlockNoteEditor-HW3TK7SM.js.map → BlockNoteEditor-PPRML5CO.js.map} +1 -1
  3. package/dist/{BlockNoteEditor-2XSIQCEB.mjs → BlockNoteEditor-UO4ZRCUM.mjs} +8 -8
  4. package/dist/{BlockNoteViewer-2UDFTXRS.mjs → BlockNoteViewer-2TJZ6JET.mjs} +6 -6
  5. package/dist/{BlockNoteViewer-4OHBRE4Q.js → BlockNoteViewer-K2HBF3IP.js} +7 -7
  6. package/dist/{BlockNoteViewer-4OHBRE4Q.js.map → BlockNoteViewer-K2HBF3IP.js.map} +1 -1
  7. package/dist/{JsonApiRequest-IKKHWCPB.mjs → JsonApiRequest-ADLBJ5RX.mjs} +2 -2
  8. package/dist/JsonApiRequest-KC6DOHKT.js +26 -0
  9. package/dist/{JsonApiRequest-G4J2WTSU.js.map → JsonApiRequest-KC6DOHKT.js.map} +1 -1
  10. package/dist/billing/index.js +495 -495
  11. package/dist/billing/index.mjs +7 -7
  12. package/dist/{chunk-N5ZE2Z6I.js → chunk-53SD4YRF.js} +5 -5
  13. package/dist/{chunk-N5ZE2Z6I.js.map → chunk-53SD4YRF.js.map} +1 -1
  14. package/dist/{chunk-4RA5PRXX.mjs → chunk-7OIWOPM5.mjs} +2 -2
  15. package/dist/{chunk-WCEYT3GG.js → chunk-A5M3MORY.js} +6 -3
  16. package/dist/chunk-A5M3MORY.js.map +1 -0
  17. package/dist/{chunk-AUD6ZLBB.mjs → chunk-BE6UMM5X.mjs} +13 -8
  18. package/dist/chunk-BE6UMM5X.mjs.map +1 -0
  19. package/dist/{chunk-KV4N7DEG.js → chunk-BQ2WAG4K.js} +29 -24
  20. package/dist/chunk-BQ2WAG4K.js.map +1 -0
  21. package/dist/{chunk-OQQ7CZWT.js → chunk-GMMDXINC.js} +12 -12
  22. package/dist/{chunk-OQQ7CZWT.js.map → chunk-GMMDXINC.js.map} +1 -1
  23. package/dist/{chunk-ZB6OYIMB.js → chunk-HN7L6RRW.js} +1296 -1093
  24. package/dist/{chunk-DPXOPLQP.mjs.map → chunk-HN7L6RRW.js.map} +1 -1
  25. package/dist/{chunk-EFQIMPCJ.mjs → chunk-HP6DT6K3.mjs} +10 -10
  26. package/dist/{chunk-JSHLBRFV.mjs → chunk-N2BFT7KI.mjs} +2 -2
  27. package/dist/chunk-N2BFT7KI.mjs.map +1 -0
  28. package/dist/{chunk-YWLSIIE6.js → chunk-P7L6OFX5.js} +11 -11
  29. package/dist/{chunk-YWLSIIE6.js.map → chunk-P7L6OFX5.js.map} +1 -1
  30. package/dist/{chunk-FXRRQ7Q6.js → chunk-R5722NLL.js} +919 -919
  31. package/dist/{chunk-FXRRQ7Q6.js.map → chunk-R5722NLL.js.map} +1 -1
  32. package/dist/{chunk-GM4VZTWL.js → chunk-RCOKQ3R4.js} +14 -8
  33. package/dist/chunk-RCOKQ3R4.js.map +1 -0
  34. package/dist/{chunk-M3N7LPHX.mjs → chunk-S7SPAC6X.mjs} +6 -3
  35. package/dist/chunk-S7SPAC6X.mjs.map +1 -0
  36. package/dist/{chunk-54K2CZ2F.js → chunk-SO3YUCL6.js} +4 -4
  37. package/dist/{chunk-54K2CZ2F.js.map → chunk-SO3YUCL6.js.map} +1 -1
  38. package/dist/{chunk-DPXOPLQP.mjs → chunk-T6G2F2BK.mjs} +220 -17
  39. package/dist/chunk-T6G2F2BK.mjs.map +1 -0
  40. package/dist/{chunk-G2UIQSNJ.mjs → chunk-TMV7TL7O.mjs} +4 -4
  41. package/dist/{chunk-BD6ARGGI.js → chunk-TNTCLVUR.js} +15 -15
  42. package/dist/{chunk-BD6ARGGI.js.map → chunk-TNTCLVUR.js.map} +1 -1
  43. package/dist/{chunk-QIEF7HIL.mjs → chunk-VNUT2D27.mjs} +2 -2
  44. package/dist/{chunk-KTGKW72G.mjs → chunk-W4ML6D2X.mjs} +2 -2
  45. package/dist/{chunk-MQ7TXALH.mjs → chunk-YMCL3JXZ.mjs} +14 -8
  46. package/dist/chunk-YMCL3JXZ.mjs.map +1 -0
  47. package/dist/{chunk-QGVVF77L.js → chunk-YSE2Z4RB.js} +11 -11
  48. package/dist/{chunk-QGVVF77L.js.map → chunk-YSE2Z4RB.js.map} +1 -1
  49. package/dist/{chunk-A3RB47X4.mjs → chunk-YTDGYI62.mjs} +3 -3
  50. package/dist/client/JsonApiClient.d.ts +5 -0
  51. package/dist/client/JsonApiClient.d.ts.map +1 -1
  52. package/dist/client/index.js +8 -8
  53. package/dist/client/index.mjs +7 -7
  54. package/dist/client/request.d.ts +5 -0
  55. package/dist/client/request.d.ts.map +1 -1
  56. package/dist/components/index.js +8 -8
  57. package/dist/components/index.mjs +7 -7
  58. package/dist/contexts/index.js +8 -8
  59. package/dist/contexts/index.mjs +7 -7
  60. package/dist/core/abstracts/AbstractService.d.ts +5 -0
  61. package/dist/core/abstracts/AbstractService.d.ts.map +1 -1
  62. package/dist/core/abstracts/ClientAbstractService.d.ts +5 -0
  63. package/dist/core/abstracts/ClientAbstractService.d.ts.map +1 -1
  64. package/dist/core/index.d.ts +2 -0
  65. package/dist/core/index.d.ts.map +1 -1
  66. package/dist/core/index.js +24 -6
  67. package/dist/core/index.js.map +1 -1
  68. package/dist/core/index.mjs +23 -5
  69. package/dist/core/registry/ModuleRegistry.d.ts +3 -0
  70. package/dist/core/registry/ModuleRegistry.d.ts.map +1 -1
  71. package/dist/email-automations/index.js +121 -121
  72. package/dist/email-automations/index.mjs +7 -7
  73. package/dist/features/analytics/index.js +139 -139
  74. package/dist/features/analytics/index.mjs +7 -7
  75. package/dist/features/analytics/server.js +9 -9
  76. package/dist/features/analytics/server.mjs +7 -7
  77. package/dist/features/blog/index.js +154 -154
  78. package/dist/features/blog/index.mjs +7 -7
  79. package/dist/features/blog/server.js +27 -27
  80. package/dist/features/blog/server.mjs +6 -6
  81. package/dist/features/discord-connection/data/discord-connect-confirmation.d.ts +11 -0
  82. package/dist/features/discord-connection/data/discord-connect-confirmation.d.ts.map +1 -0
  83. package/dist/features/discord-connection/data/discord-connect-confirmation.interface.d.ts +14 -0
  84. package/dist/features/discord-connection/data/discord-connect-confirmation.interface.d.ts.map +1 -0
  85. package/dist/features/discord-connection/data/discord-connect-confirmation.service.d.ts +10 -0
  86. package/dist/features/discord-connection/data/discord-connect-confirmation.service.d.ts.map +1 -0
  87. package/dist/features/discord-connection/data/discord-connect-intent.d.ts +11 -0
  88. package/dist/features/discord-connection/data/discord-connect-intent.d.ts.map +1 -0
  89. package/dist/features/discord-connection/data/discord-connect-intent.interface.d.ts +15 -0
  90. package/dist/features/discord-connection/data/discord-connect-intent.interface.d.ts.map +1 -0
  91. package/dist/features/discord-connection/data/discord-connect-intent.service.d.ts +11 -0
  92. package/dist/features/discord-connection/data/discord-connect-intent.service.d.ts.map +1 -0
  93. package/dist/features/discord-connection/data/discord-connection.d.ts +14 -0
  94. package/dist/features/discord-connection/data/discord-connection.d.ts.map +1 -0
  95. package/dist/features/discord-connection/data/discord-connection.interface.d.ts +10 -0
  96. package/dist/features/discord-connection/data/discord-connection.interface.d.ts.map +1 -0
  97. package/dist/features/discord-connection/data/discord-connection.service.d.ts +12 -0
  98. package/dist/features/discord-connection/data/discord-connection.service.d.ts.map +1 -0
  99. package/dist/features/discord-connection/data/index.d.ts +10 -0
  100. package/dist/features/discord-connection/data/index.d.ts.map +1 -0
  101. package/dist/features/discord-connection/discord-connection.module.d.ts +5 -0
  102. package/dist/features/discord-connection/discord-connection.module.d.ts.map +1 -0
  103. package/dist/features/discord-connection/index.d.ts +3 -0
  104. package/dist/features/discord-connection/index.d.ts.map +1 -0
  105. package/dist/features/help/index.js +41 -41
  106. package/dist/features/help/index.mjs +7 -7
  107. package/dist/features/tokenusage/index.js +130 -130
  108. package/dist/features/tokenusage/index.mjs +7 -7
  109. package/dist/index.d.ts +1 -1
  110. package/dist/index.d.ts.map +1 -1
  111. package/dist/index.js +27 -7
  112. package/dist/index.js.map +1 -1
  113. package/dist/index.mjs +26 -6
  114. package/dist/local-transport-MJPOKPTU.js +15 -0
  115. package/dist/{local-transport-4YDJ6FQG.js.map → local-transport-MJPOKPTU.js.map} +1 -1
  116. package/dist/{local-transport-C7YTA4I7.mjs → local-transport-RVD4FZGA.mjs} +5 -5
  117. package/dist/offline/index.js +51 -51
  118. package/dist/offline/index.mjs +6 -6
  119. package/dist/{request-66FGJIHB.mjs → request-4AWGPIGH.mjs} +2 -2
  120. package/dist/{request-6W6UGKJV.js → request-H5FZBZA2.js} +3 -3
  121. package/dist/{request-6W6UGKJV.js.map → request-H5FZBZA2.js.map} +1 -1
  122. package/dist/server/index.js +8 -8
  123. package/dist/server/index.mjs +7 -7
  124. package/dist/unified/JsonApiRequest.d.ts +5 -0
  125. package/dist/unified/JsonApiRequest.d.ts.map +1 -1
  126. package/dist/write-through-7I3LA2WN.mjs +15 -0
  127. package/dist/write-through-HE2QSOVI.js +15 -0
  128. package/dist/{write-through-BAPS24GL.js.map → write-through-HE2QSOVI.js.map} +1 -1
  129. package/package.json +1 -1
  130. package/src/client/JsonApiClient.ts +10 -0
  131. package/src/client/__tests__/request.credentials.spec.ts +103 -0
  132. package/src/client/request.ts +9 -0
  133. package/src/core/abstracts/AbstractService.ts +10 -0
  134. package/src/core/abstracts/ClientAbstractService.ts +10 -0
  135. package/src/core/index.ts +3 -0
  136. package/src/core/registry/ModuleRegistry.ts +4 -0
  137. package/src/features/discord-connection/data/__tests__/DiscordConnection.spec.ts +114 -0
  138. package/src/features/discord-connection/data/discord-connect-confirmation.interface.ts +16 -0
  139. package/src/features/discord-connection/data/discord-connect-confirmation.service.ts +21 -0
  140. package/src/features/discord-connection/data/discord-connect-confirmation.ts +46 -0
  141. package/src/features/discord-connection/data/discord-connect-intent.interface.ts +16 -0
  142. package/src/features/discord-connection/data/discord-connect-intent.service.ts +20 -0
  143. package/src/features/discord-connection/data/discord-connect-intent.ts +42 -0
  144. package/src/features/discord-connection/data/discord-connection.interface.ts +10 -0
  145. package/src/features/discord-connection/data/discord-connection.service.ts +17 -0
  146. package/src/features/discord-connection/data/discord-connection.ts +41 -0
  147. package/src/features/discord-connection/data/index.ts +9 -0
  148. package/src/features/discord-connection/discord-connection.module.ts +28 -0
  149. package/src/features/discord-connection/index.ts +2 -0
  150. package/src/index.ts +1 -1
  151. package/src/unified/JsonApiRequest.ts +14 -0
  152. package/dist/JsonApiRequest-G4J2WTSU.js +0 -26
  153. package/dist/chunk-AUD6ZLBB.mjs.map +0 -1
  154. package/dist/chunk-GM4VZTWL.js.map +0 -1
  155. package/dist/chunk-JSHLBRFV.mjs.map +0 -1
  156. package/dist/chunk-KV4N7DEG.js.map +0 -1
  157. package/dist/chunk-M3N7LPHX.mjs.map +0 -1
  158. package/dist/chunk-MQ7TXALH.mjs.map +0 -1
  159. package/dist/chunk-WCEYT3GG.js.map +0 -1
  160. package/dist/chunk-ZB6OYIMB.js.map +0 -1
  161. package/dist/local-transport-4YDJ6FQG.js +0 -15
  162. package/dist/write-through-BAPS24GL.js +0 -15
  163. package/dist/write-through-IWQKXYHE.mjs +0 -15
  164. /package/dist/{BlockNoteEditor-2XSIQCEB.mjs.map → BlockNoteEditor-UO4ZRCUM.mjs.map} +0 -0
  165. /package/dist/{BlockNoteViewer-2UDFTXRS.mjs.map → BlockNoteViewer-2TJZ6JET.mjs.map} +0 -0
  166. /package/dist/{JsonApiRequest-IKKHWCPB.mjs.map → JsonApiRequest-ADLBJ5RX.mjs.map} +0 -0
  167. /package/dist/{chunk-4RA5PRXX.mjs.map → chunk-7OIWOPM5.mjs.map} +0 -0
  168. /package/dist/{chunk-EFQIMPCJ.mjs.map → chunk-HP6DT6K3.mjs.map} +0 -0
  169. /package/dist/{chunk-G2UIQSNJ.mjs.map → chunk-TMV7TL7O.mjs.map} +0 -0
  170. /package/dist/{chunk-QIEF7HIL.mjs.map → chunk-VNUT2D27.mjs.map} +0 -0
  171. /package/dist/{chunk-KTGKW72G.mjs.map → chunk-W4ML6D2X.mjs.map} +0 -0
  172. /package/dist/{chunk-A3RB47X4.mjs.map → chunk-YTDGYI62.mjs.map} +0 -0
  173. /package/dist/{local-transport-C7YTA4I7.mjs.map → local-transport-RVD4FZGA.mjs.map} +0 -0
  174. /package/dist/{request-66FGJIHB.mjs.map → request-4AWGPIGH.mjs.map} +0 -0
  175. /package/dist/{write-through-IWQKXYHE.mjs.map → write-through-7I3LA2WN.mjs.map} +0 -0
@@ -81,11 +81,11 @@ import {
81
81
  useCurrentUserContext,
82
82
  useDataListRetriever,
83
83
  usePageUrlGenerator
84
- } from "../chunk-EFQIMPCJ.mjs";
84
+ } from "../chunk-HP6DT6K3.mjs";
85
85
  import "../chunk-VOXD3ZLY.mjs";
86
86
  import {
87
87
  getStripePublishableKey
88
- } from "../chunk-G2UIQSNJ.mjs";
88
+ } from "../chunk-TMV7TL7O.mjs";
89
89
  import {
90
90
  getRoleId
91
91
  } from "../chunk-PW42LRSL.mjs";
@@ -112,17 +112,17 @@ import {
112
112
  resolveChangePlanTarget,
113
113
  showToast,
114
114
  toPromotionCodeResult
115
- } from "../chunk-DPXOPLQP.mjs";
115
+ } from "../chunk-T6G2F2BK.mjs";
116
116
  import "../chunk-OY65RYD3.mjs";
117
117
  import {
118
118
  Modules,
119
119
  useI18nLocale,
120
120
  useI18nRouter
121
- } from "../chunk-JSHLBRFV.mjs";
122
- import "../chunk-AUD6ZLBB.mjs";
123
- import "../chunk-M3N7LPHX.mjs";
121
+ } from "../chunk-N2BFT7KI.mjs";
122
+ import "../chunk-BE6UMM5X.mjs";
123
+ import "../chunk-S7SPAC6X.mjs";
124
124
  import "../chunk-4ZJIUTIV.mjs";
125
- import "../chunk-MQ7TXALH.mjs";
125
+ import "../chunk-YMCL3JXZ.mjs";
126
126
  import "../chunk-AUXK7QSA.mjs";
127
127
  import {
128
128
  __name
@@ -1,7 +1,7 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
2
 
3
3
 
4
- var _chunkKV4N7DEGjs = require('./chunk-KV4N7DEG.js');
4
+ var _chunkBQ2WAG4Kjs = require('./chunk-BQ2WAG4K.js');
5
5
 
6
6
 
7
7
 
@@ -12,7 +12,7 @@ var _chunkKV4N7DEGjs = require('./chunk-KV4N7DEG.js');
12
12
  var _chunkWUNSG3INjs = require('./chunk-WUNSG3IN.js');
13
13
 
14
14
 
15
- var _chunkGM4VZTWLjs = require('./chunk-GM4VZTWL.js');
15
+ var _chunkRCOKQ3R4js = require('./chunk-RCOKQ3R4.js');
16
16
 
17
17
 
18
18
  var _chunk7QVYU63Ejs = require('./chunk-7QVYU63E.js');
@@ -92,7 +92,7 @@ _chunk7QVYU63Ejs.__name.call(void 0, includedFor, "includedFor");
92
92
  function signedInUserResource(target) {
93
93
  try {
94
94
  if (target.id !== _chunkWUNSG3INjs.getOfflineConfig.call(void 0, ).getUserId()) return void 0;
95
- const stored = JSON.parse(_nullishCoalesce(window.localStorage.getItem(_chunkKV4N7DEGjs.CURRENT_USER_STORAGE_KEY), () => ( "null")));
95
+ const stored = JSON.parse(_nullishCoalesce(window.localStorage.getItem(_chunkBQ2WAG4Kjs.CURRENT_USER_STORAGE_KEY), () => ( "null")));
96
96
  const user = _optionalChain([stored, 'optionalAccess', _7 => _7.jsonApi]);
97
97
  if (_optionalChain([user, 'optionalAccess', _8 => _8.type]) !== target.type || _optionalChain([user, 'optionalAccess', _9 => _9.id]) !== target.id) return void 0;
98
98
  return { type: user.type, id: user.id, attributes: _nullishCoalesce(user.attributes, () => ( {})), meta: user.meta };
@@ -571,7 +571,7 @@ _chunk7QVYU63Ejs.__name.call(void 0, matchRoute, "matchRoute");
571
571
  var METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"];
572
572
  function apiBases() {
573
573
  const bases = [];
574
- for (const read of [_chunkGM4VZTWLjs.getApiUrl, _chunkKV4N7DEGjs.getClientApiUrl]) {
574
+ for (const read of [_chunkRCOKQ3R4js.getApiUrl, _chunkBQ2WAG4Kjs.getClientApiUrl]) {
575
575
  try {
576
576
  const base = read();
577
577
  if (base) bases.push(base);
@@ -725,4 +725,4 @@ _chunk7QVYU63Ejs.__name.call(void 0, localTransport, "localTransport");
725
725
 
726
726
 
727
727
  exports.errorAnswer = errorAnswer; exports.needsConnectionAnswer = needsConnectionAnswer; exports.notFoundAnswer = notFoundAnswer; exports.singleAnswer = singleAnswer; exports.includedFor = includedFor; exports.SERVER_DEFAULT_ORDER_BY = SERVER_DEFAULT_ORDER_BY; exports.searchRecords = searchRecords; exports.orderRecords = orderRecords; exports.listAnswer = listAnswer; exports.orderedListAnswer = orderedListAnswer; exports.resourceListAnswer = resourceListAnswer; exports.linkKindFor = linkKindFor; exports.linkKindsOf = linkKindsOf; exports.linksOfKind = linksOfKind; exports.rootIdForResource = rootIdForResource; exports.resourceFromDocument = resourceFromDocument; exports.mergeResource = mergeResource; exports.matchPattern = matchPattern; exports.matchRoute = matchRoute; exports.splitApiUrl = splitApiUrl; exports.localTransport = localTransport;
728
- //# sourceMappingURL=chunk-N5ZE2Z6I.js.map
728
+ //# sourceMappingURL=chunk-53SD4YRF.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/nextjs-jsonapi/nextjs-jsonapi/dist/chunk-N5ZE2Z6I.js","../src/offline/generic-answers.ts","../src/offline/router.ts","../src/offline/local-trans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":"/home/runner/work/nextjs-jsonapi/nextjs-jsonapi/dist/chunk-N5ZE2Z6I.js","sourcesContent":[null,"import { CURRENT_USER_STORAGE_KEY } from \"../features/user/data/user.storage\";\nimport { getOfflineConfig, rootKinds } from \"./config\";\nimport { getOfflineState } from \"./state\";\nimport type { DeviceStore, StoredLink, StoredRecord } from \"./store/DeviceStore\";\nimport type {\n LocalAnswerContext,\n OfflineAnswer,\n OfflineConfig,\n OfflineMethod,\n OfflineRootKind,\n OfflineRoute,\n OfflineTypeConfig,\n} from \"./types\";\n\nconst DEFAULT_PAGE_SIZE = 25;\n\n// ---------------------------------------------------------------------------------------------\n// Answers shared by every route\n// ---------------------------------------------------------------------------------------------\n\n/** A JSON:API errors document with one error, answered with `status`. */\nexport function errorAnswer(status: number, title: string, detail: string, code?: string): OfflineAnswer {\n return {\n status,\n body: { errors: [{ status: String(status), ...(code ? { code } : {}), title, detail }] },\n };\n}\n\nexport function needsConnectionAnswer(detail: string = \"Needs a connection\"): OfflineAnswer {\n return errorAnswer(503, \"Needs a connection\", detail, \"needs-connection\");\n}\n\nexport function notFoundAnswer(detail: string): OfflineAnswer {\n return errorAnswer(404, \"Not found\", detail);\n}\n\n/** A single document of one stored record, with `included` (`includedFor`). */\nexport async function singleAnswer(\n store: DeviceStore,\n record: StoredRecord,\n status: number = 200,\n): Promise<OfflineAnswer> {\n return { status, body: { data: record.resource, included: await includedFor(store, [record]) } };\n}\n\nexport function isRootWriteLocked(rootId: string | undefined): boolean {\n return !!rootId && getOfflineState().lockedRootIds.includes(rootId);\n}\n\n// ---------------------------------------------------------------------------------------------\n// Resource helpers\n// ---------------------------------------------------------------------------------------------\n\ntype ResourceIdentifier = { type: string; id: string };\n\nfunction identifiersOf(relationship: any): ResourceIdentifier[] {\n const data = relationship?.data;\n if (!data) return [];\n return (Array.isArray(data) ? data : [data]).filter((item: any) => item && item.type && item.id);\n}\n\nfunction linkedIds(links: StoredLink[], id: string): ResourceIdentifier[] {\n return links.map((link) =>\n link.fromId === id ? { type: link.toType, id: link.toId } : { type: link.fromType, id: link.fromId },\n );\n}\n\n/** Every stored resource linked to one of `ids`, in either direction, without duplicates or the records themselves. */\n/** The `{ type, id }` every relationship of a JSON:API resource points to. */\nfunction relationshipTargets(resource: any): { type: string; id: string }[] {\n const targets: { type: string; id: string }[] = [];\n for (const relationship of Object.values<any>(resource?.relationships ?? {})) {\n const data = relationship?.data;\n for (const ref of Array.isArray(data) ? data : data ? [data] : []) {\n if (ref?.type && ref?.id) targets.push({ type: ref.type, id: ref.id });\n }\n }\n return targets;\n}\n\n/**\n * The `included` of a local answer: the stored records linked to `records` (the synced links),\n * then the stored records their relationships point to, and one level further the stored records\n * the relationships of those included records point to (an NPC's root record, then the root record's\n * owner), so a model reads the same nested relationships it reads from the server.\n *\n * Stored resources point at each other (a root record at its owner, the owner at the root record's\n * company, the company back at the owner); `RehydrationFactory` skips a resource met again inside\n * its own chain, so those circles never recurse.\n */\nexport async function includedFor(store: DeviceStore, records: StoredRecord[]): Promise<any[]> {\n // 0: the answer's own records; 1: what they link to; 2: what those link to.\n const level = new Map<string, number>(records.map((record) => [`${record.type}:${record.id}`, 0]));\n const included: { resource: any; level: number }[] = [];\n\n const add = async (target: { type: string; id: string }, atLevel: number): Promise<void> => {\n const key = `${target.type}:${target.id}`;\n if (level.has(key)) return;\n level.set(key, atLevel);\n const stored = await store.getRecord(target.type, target.id);\n const resource = stored?.resource ?? signedInUserResource(target);\n if (resource) included.push({ resource, level: atLevel });\n };\n\n for (const record of records) {\n const links = [...(await store.linksFrom(record.id)), ...(await store.linksTo(record.id))];\n for (const target of linkedIds(links, record.id)) await add(target, 1);\n }\n for (const record of records) {\n for (const target of relationshipTargets(record.resource)) await add(target, 1);\n }\n for (const entry of included.filter((candidate) => candidate.level === 1)) {\n for (const target of relationshipTargets(entry.resource)) await add(target, 2);\n }\n return included.map((entry) => entry.resource);\n}\n\n/**\n * The signed-in user as a resource, when `target` is that user. Users are not kept on the device,\n * but a relationship to the signed-in user (every downloaded root record's owner) must still resolve:\n * the app tells a GM from a player by comparing the root record's owner with the signed-in user. The\n * resource comes from the copy CurrentUserProvider keeps in localStorage, without relationships.\n */\nfunction signedInUserResource(target: { type: string; id: string }): any | undefined {\n try {\n if (target.id !== getOfflineConfig().getUserId()) return undefined;\n const stored = JSON.parse(window.localStorage.getItem(CURRENT_USER_STORAGE_KEY) ?? \"null\");\n const user = stored?.jsonApi;\n if (user?.type !== target.type || user?.id !== target.id) return undefined;\n return { type: user.type, id: user.id, attributes: user.attributes ?? {}, meta: user.meta };\n } catch {\n return undefined;\n }\n}\n\nfunction attributeOf(record: StoredRecord, name: string): unknown {\n const value = record.resource?.attributes?.[name];\n if (value !== undefined && value !== null) return value;\n // The server value the sync keeps beside the resource.\n if (name === \"updatedAt\") return record.updatedAt ?? null;\n return value;\n}\n\n/** The server's default list order (`defineEntity` sets `defaultOrderBy: \"updatedAt DESC\"`). */\nexport const SERVER_DEFAULT_ORDER_BY = \"updatedAt DESC\";\n\n/** The only `orderBy` the server accepts (`buildLegacyOrderByClause`): one property, optional ASC/DESC. */\nconst ORDER_BY = /^([A-Za-z_][A-Za-z0-9_]*)(?:\\s+(ASC|DESC))?$/i;\n\nconst ISO_DATE = /^\\d{4}-\\d{2}-\\d{2}(T|$)/;\n\nfunction comparable(value: unknown): unknown {\n if (value instanceof Date) return value.getTime();\n if (typeof value === \"string\" && ISO_DATE.test(value)) {\n const time = Date.parse(value);\n if (!Number.isNaN(time)) return time;\n }\n return value;\n}\n\n/** Cypher ORDER BY on one property, ascending: null sorts after every value. */\nfunction compareAscending(left: unknown, right: unknown): number {\n const a = comparable(left);\n const b = comparable(right);\n const aNull = a === undefined || a === null;\n const bNull = b === undefined || b === null;\n if (aNull || bNull) return aNull === bNull ? 0 : aNull ? 1 : -1;\n if (typeof a === \"number\" && typeof b === \"number\") return a - b;\n if (typeof a === \"boolean\" && typeof b === \"boolean\") return Number(a) - Number(b);\n const x = String(a);\n const y = String(b);\n return x < y ? -1 : x > y ? 1 : 0;\n}\n\nexport type ListOptions = {\n /** The string attributes the server's fulltext index covers (default: every string attribute). */\n searchFields?: string[];\n /** The order with no `orderBy` (default `updatedAt DESC`, the server's). */\n defaultOrderBy?: string;\n};\n\n/**\n * `search` as the server runs it: the term is split into letter/digit tokens and a record\n * matches when every token appears, case-insensitive, inside one of its indexed string\n * attributes (the fulltext query `*token* AND ...`).\n */\nexport function searchRecords(\n records: StoredRecord[],\n query: URLSearchParams,\n options: ListOptions = {},\n): StoredRecord[] {\n const term = query.get(\"search\");\n if (term === null || term === undefined || term.trim() === \"\") return records;\n const tokens = term\n .toLowerCase()\n .split(/[^\\p{L}\\p{N}]+/u)\n .filter(Boolean);\n if (tokens.length === 0) return records;\n\n return records.filter((record) => {\n const attributes = record.resource?.attributes ?? {};\n const fields = options.searchFields ?? Object.keys(attributes);\n const texts = fields\n .map((field) => attributes[field])\n .filter((value): value is string => typeof value === \"string\")\n .map((value) => value.toLowerCase());\n return tokens.every((token) => texts.some((text) => text.includes(token)));\n });\n}\n\n/**\n * Orders records as the server's `ORDER BY` does for `orderBy` (`field` or `field ASC|DESC`),\n * or for the default order when there is none. `null` when the server would refuse the\n * `orderBy` (400).\n */\nexport function orderRecords(\n records: StoredRecord[],\n query: URLSearchParams,\n options: ListOptions = {},\n): StoredRecord[] | null {\n const requested = query.get(\"orderBy\")?.trim();\n const value = requested || options.defaultOrderBy?.trim() || SERVER_DEFAULT_ORDER_BY;\n const match = ORDER_BY.exec(value);\n if (!match) return null;\n const field = match[1];\n const desc = match[2]?.toUpperCase() === \"DESC\";\n return [...records].sort((left, right) => {\n const order = compareAscending(attributeOf(left, field), attributeOf(right, field));\n return desc ? -order : order;\n });\n}\n\nfunction linkUrl(base: string, query: URLSearchParams, changes: Record<string, string | undefined>): string {\n const params = new URLSearchParams(query);\n for (const [key, value] of Object.entries(changes)) {\n if (value === undefined) params.delete(key);\n else params.set(key, value);\n }\n const search = params.toString().replace(/%5B/g, \"[\").replace(/%5D/g, \"]\").replace(/%2C/g, \",\");\n return search ? `${base}?${search}` : base;\n}\n\n/**\n * One list answer for a set of stored records, as the server answers a list: `search`, then\n * `orderBy` (or the default order), then paged the way `JsonApiPaginator` pages (`fetchAll`,\n * `page[size]`, `page[offset]`), with `included`. App answers pass the records they selected.\n */\nexport async function listAnswer(\n ctx: LocalAnswerContext,\n records: StoredRecord[],\n options: ListOptions = {},\n): Promise<OfflineAnswer> {\n const { request, store } = ctx;\n const base = request.url ? request.url.split(\"?\")[0] : request.path;\n const sorted = orderRecords(searchRecords(records, request.query, options), request.query, options);\n if (!sorted) {\n return errorAnswer(400, \"Bad Request\", \"Invalid orderBy\");\n }\n\n if (request.query.get(\"fetchAll\") === \"true\") {\n return {\n status: 200,\n body: {\n data: sorted.map((record) => record.resource),\n included: await includedFor(store, sorted),\n links: { self: linkUrl(base, request.query, {}) },\n meta: { total: sorted.length },\n },\n };\n }\n\n const size = Number(request.query.get(\"page[size]\")) || DEFAULT_PAGE_SIZE;\n const offset = Number(request.query.get(\"page[offset]\")) || 0;\n const page = sorted.slice(offset, offset + size);\n\n const links: Record<string, string> = {\n self: linkUrl(base, request.query, { \"page[size]\": String(size), \"page[offset]\": undefined }),\n };\n if (offset + size < sorted.length) {\n links.next = linkUrl(base, request.query, { \"page[size]\": String(size), \"page[offset]\": String(offset + size) });\n }\n if (offset > 0) {\n links.prev = linkUrl(base, request.query, {\n \"page[size]\": String(size),\n \"page[offset]\": String(Math.max(0, offset - size)),\n });\n // The server names it `previous`; the client reads `prev`.\n links.previous = links.prev;\n }\n\n return {\n status: 200,\n body: {\n data: page.map((record) => record.resource),\n included: await includedFor(store, page),\n links,\n meta: { total: sorted.length },\n },\n };\n}\n\n/**\n * A list document of stored records in the order the caller settled, every record in one page,\n * with `included`: for an app's custom list query that has its own `ORDER BY` and no paging.\n */\nexport async function orderedListAnswer(store: DeviceStore, records: StoredRecord[]): Promise<OfflineAnswer> {\n return {\n status: 200,\n body: {\n data: records.map((record) => record.resource),\n included: await includedFor(store, records),\n meta: { total: records.length },\n },\n };\n}\n\n/**\n * A list document of resources the device computed rather than stored (a query-result\n * projection such as a search hit, built by its model), answered as they are, nothing included.\n */\nexport function resourceListAnswer(resources: any[]): OfflineAnswer {\n return { status: 200, body: { data: resources, included: [] } };\n}\n\nfunction listOptionsOf(typeConfig: OfflineTypeConfig): ListOptions {\n return { searchFields: typeConfig.searchFields, defaultOrderBy: typeConfig.defaultOrderBy };\n}\n\n// ---------------------------------------------------------------------------------------------\n// Link kinds\n// ---------------------------------------------------------------------------------------------\n\n/**\n * The kind a link written on the device carries for relationship `name`: the Neo4j type the\n * type config maps it to (the kind synced links carry), otherwise the name itself.\n */\nexport function linkKindFor(typeConfig: OfflineTypeConfig | undefined, name: string): string {\n return typeConfig?.relationshipKinds?.[name] ?? name;\n}\n\n/**\n * Every kind a link of relationship `name` may carry on the device: the name (written on the\n * device before a mapping existed) and the mapped Neo4j type (synced). `undefined` when the\n * Neo4j type is not known: then a link of any kind may be the one.\n */\nexport function linkKindsOf(typeConfig: OfflineTypeConfig | undefined, name: string): string[] | undefined {\n const mapped = typeConfig?.relationshipKinds?.[name];\n return mapped ? [name, mapped] : undefined;\n}\n\n/**\n * The stored links of `id` whose kind is one of `kinds` (Neo4j types and/or relationship\n * names). `out`: links from `id`; `in`: links to `id`; `both`: either.\n */\nexport async function linksOfKind(\n store: DeviceStore,\n id: string,\n kinds: string[],\n direction: \"out\" | \"in\" | \"both\" = \"both\",\n): Promise<StoredLink[]> {\n const result: StoredLink[] = [];\n const seen = new Set<string>();\n for (const kind of new Set(kinds)) {\n const links = [\n ...(direction !== \"in\" ? await store.linksFrom(id, kind) : []),\n ...(direction !== \"out\" ? await store.linksTo(id, kind) : []),\n ];\n for (const link of links) {\n const key = `${link.fromId}|${link.toId}|${link.kind}`;\n if (seen.has(key)) continue;\n seen.add(key);\n result.push(link);\n }\n }\n return result;\n}\n\nfunction typeConfigOf(config: OfflineConfig, type: string): OfflineTypeConfig | undefined {\n return config.types.find((typeConfig) => typeConfig.module.name === type);\n}\n\n/** The relationship names of `resource` that point to a record of `type`. */\nfunction relationshipNamesToward(resource: any, type: string): string[] {\n return Object.entries<any>(resource?.relationships ?? {})\n .filter(([, relationship]) => identifiersOf(relationship).some((identifier) => identifier.type === type))\n .map(([name]) => name);\n}\n\n// ---------------------------------------------------------------------------------------------\n// Reads\n// ---------------------------------------------------------------------------------------------\n\n/** A record that is not on the device: only the server can answer for it. */\nfunction notOnDeviceAnswer(type: string, id: string): OfflineAnswer {\n return needsConnectionAnswer(`${type} ${id} is not on this device`);\n}\n\nasync function getOne(ctx: LocalAnswerContext, type: string): Promise<OfflineAnswer> {\n const record = await ctx.store.getRecord(type, ctx.params.id);\n if (!record) return notOnDeviceAnswer(type, ctx.params.id);\n return singleAnswer(ctx.store, record);\n}\n\nasync function rootList(\n ctx: LocalAnswerContext,\n kind: OfflineRootKind,\n typeConfig: OfflineTypeConfig,\n): Promise<OfflineAnswer> {\n const rootType = kind.module.name;\n const rootId = ctx.params.rootId;\n if (!(await ctx.store.getRecord(rootType, rootId))) return notOnDeviceAnswer(rootType, rootId);\n const records = await ctx.store.listRecords({ type: typeConfig.module.name, rootId });\n return listAnswer(ctx, records, listOptionsOf(typeConfig));\n}\n\n/**\n * `GET <parent>/:parentId/<type>`: the stored records of `type` linked to the parent by the\n * relationship between the two types. That relationship is the one whose name, on either\n * record, points to the other type; its links are matched by name and by mapped Neo4j type.\n * When its Neo4j type is not known, links of any kind count.\n */\nasync function relatedList(\n ctx: LocalAnswerContext,\n config: OfflineConfig,\n typeConfig: OfflineTypeConfig,\n): Promise<OfflineAnswer> {\n const type = typeConfig.module.name;\n const { parentType, parentId } = ctx.params;\n const parent = await ctx.store.getRecord(parentType, parentId);\n if (!parent) return notOnDeviceAnswer(parentType, parentId);\n\n const links = [...(await ctx.store.linksFrom(parentId)), ...(await ctx.store.linksTo(parentId))].filter((link) =>\n link.fromId === parentId ? link.toType === type : link.fromType === type,\n );\n const candidates = await ctx.store.listRecords({\n type,\n ids: [...new Set(links.map((link) => (link.fromId === parentId ? link.toId : link.fromId)))],\n });\n\n const kinds = new Set<string>();\n let anyKind = false;\n const collect = (owner: OfflineTypeConfig | undefined, names: string[]) => {\n for (const name of names) {\n const known = linkKindsOf(owner, name);\n if (known) known.forEach((kind) => kinds.add(kind));\n else anyKind = true;\n }\n };\n collect(typeConfig, [\n ...new Set(candidates.flatMap((record) => relationshipNamesToward(record.resource, parentType))),\n ]);\n collect(typeConfigOf(config, parentType), relationshipNamesToward(parent.resource, type));\n\n const accepted = anyKind || kinds.size === 0 ? links : links.filter((link) => kinds.has(link.kind));\n const ids = new Set(accepted.map((link) => (link.fromId === parentId ? link.toId : link.fromId)));\n return listAnswer(\n ctx,\n candidates.filter((record) => ids.has(record.id)),\n listOptionsOf(typeConfig),\n );\n}\n\n// ---------------------------------------------------------------------------------------------\n// Writes\n// ---------------------------------------------------------------------------------------------\n\n/**\n * The root record a record belongs to: itself (the type of any root kind), a relationship to a\n * root of any kind, or a related stored record.\n */\nexport async function rootIdForResource(\n store: DeviceStore,\n config: OfflineConfig,\n resource: any,\n): Promise<string | undefined> {\n const rootTypes = new Set(rootKinds(config).map((kind) => kind.module.name));\n if (rootTypes.has(resource?.type) && resource.id) return resource.id;\n\n const identifiers = Object.values(resource?.relationships ?? {}).flatMap(identifiersOf);\n const root = identifiers.find((identifier) => rootTypes.has(identifier.type));\n if (root) return root.id;\n\n for (const identifier of identifiers) {\n const stored = await store.getRecord(identifier.type, identifier.id);\n if (stored?.rootId) return stored.rootId;\n }\n return undefined;\n}\n\nasync function linkRelationships(\n store: DeviceStore,\n typeConfig: OfflineTypeConfig | undefined,\n record: { type: string; id: string },\n before: Record<string, any>,\n after: Record<string, any>,\n): Promise<void> {\n for (const [name, relationship] of Object.entries(after)) {\n const previous = new Map(identifiersOf(before[name]).map((identifier) => [identifier.id, identifier]));\n const next = new Map(identifiersOf(relationship).map((identifier) => [identifier.id, identifier]));\n const kinds = linkKindsOf(typeConfig, name);\n\n for (const [id] of previous) {\n if (next.has(id)) continue;\n // Only the links of this relationship (by name or Neo4j type); any kind when it is not known.\n const links = kinds\n ? await linksOfKind(store, record.id, kinds, \"both\")\n : [...(await store.linksFrom(record.id)), ...(await store.linksTo(record.id))];\n for (const link of links) {\n if (link.fromId === id || link.toId === id) {\n await store.deleteLink({ fromId: link.fromId, toId: link.toId, kind: link.kind });\n }\n }\n }\n for (const [id, identifier] of next) {\n if (previous.has(id)) continue;\n await store.putLink({\n fromType: record.type,\n fromId: record.id,\n toType: identifier.type,\n toId: id,\n kind: linkKindFor(typeConfig, name),\n props: {},\n });\n }\n }\n}\n\n/** The `data` of a JSON:API document a model built (`createJsonApi()` or a dedicated method). */\nexport type ResourceDocumentData = {\n attributes?: Record<string, unknown>;\n relationships?: Record<string, unknown>;\n meta?: Record<string, unknown>;\n};\n\n/**\n * The resource a create document stands for, under `identity`: the document's attributes,\n * relationships and meta, as the device stores a record it creates.\n */\nexport function resourceFromDocument(document: any, identity: { type: string; id: string }): any {\n const data: ResourceDocumentData = document?.data ?? {};\n const resource: any = { type: identity.type, id: identity.id };\n if (data.attributes) resource.attributes = { ...data.attributes };\n if (data.relationships) resource.relationships = { ...data.relationships };\n if (data.meta) resource.meta = { ...data.meta };\n return resource;\n}\n\n/**\n * A stored resource with a document's `data` written over it: attributes and relationships merged\n * by name, and meta merged when the document carries one, as the device applies an edit.\n */\nexport function mergeResource(before: any, identity: { type: string; id: string }, data: ResourceDocumentData): any {\n const previous = before ?? identity;\n const resource: any = {\n ...previous,\n type: identity.type,\n id: identity.id,\n attributes: { ...(previous.attributes ?? {}), ...(data?.attributes ?? {}) },\n relationships: { ...(previous.relationships ?? {}), ...(data?.relationships ?? {}) },\n };\n if (data?.meta) resource.meta = { ...(previous.meta ?? {}), ...data.meta };\n return resource;\n}\n\nfunction newId(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") return crypto.randomUUID();\n return `local-${Date.now()}-${Math.random().toString(16).slice(2)}`;\n}\n\nasync function create(ctx: LocalAnswerContext, config: OfflineConfig, type: string): Promise<OfflineAnswer> {\n const typeConfig = typeConfigOf(config, type);\n const id: string = ctx.request.body?.data?.id ?? newId();\n const resource = resourceFromDocument(ctx.request.body, { type, id });\n const rootId = await rootIdForResource(ctx.store, config, resource);\n if (!rootId) return needsConnectionAnswer(`A new ${type} that belongs to no root record needs a connection`);\n if (isRootWriteLocked(rootId)) return needsConnectionAnswer(\"The root record is locked\");\n\n const record: StoredRecord = { type, id, rootId, resource, updatedAt: null, base: null, localOnly: true };\n await ctx.store.transaction(async (store) => {\n await store.putRecord(record);\n await linkRelationships(store, typeConfig, { type, id }, {}, resource.relationships ?? {});\n await store.enqueue({\n rootId,\n method: ctx.request.method,\n path: queuePath(ctx),\n body: ctx.request.body,\n base: null,\n });\n // The type's hook, inside the write's transaction: a throw rolls the write and the enqueue back.\n if (typeConfig?.afterLocalWrite) {\n await typeConfig.afterLocalWrite({\n store,\n module: typeConfig.module,\n id,\n method: \"POST\",\n resource,\n previous: null,\n });\n }\n });\n\n return singleAnswer(ctx.store, record, 201);\n}\n\nasync function update(ctx: LocalAnswerContext, config: OfflineConfig, type: string): Promise<OfflineAnswer> {\n const id = ctx.params.id;\n const existing = await ctx.store.getRecord(type, id);\n if (!existing) return notOnDeviceAnswer(type, id);\n if (isRootWriteLocked(existing.rootId)) return needsConnectionAnswer(\"The root record is locked\");\n\n const data = ctx.request.body?.data ?? {};\n const before = existing.resource ?? { type, id };\n const resource = mergeResource(before, { type, id }, data);\n // A record created on this device has no server version to merge against.\n const base = existing.localOnly ? null : (existing.base ?? before);\n\n const typeConfig = typeConfigOf(config, type);\n const method = ctx.request.method === \"PATCH\" ? \"PATCH\" : \"PUT\";\n const record: StoredRecord = { ...existing, resource, base, localOnly: existing.localOnly };\n await ctx.store.transaction(async (store) => {\n await store.putRecord(record);\n await linkRelationships(store, typeConfig, { type, id }, before.relationships ?? {}, data.relationships ?? {});\n await store.enqueue({\n rootId: existing.rootId,\n method: ctx.request.method,\n path: queuePath(ctx),\n body: ctx.request.body,\n recordType: type,\n recordId: id,\n base,\n });\n if (typeConfig?.afterLocalWrite) {\n await typeConfig.afterLocalWrite({ store, module: typeConfig.module, id, method, resource, previous: before });\n }\n });\n\n return singleAnswer(ctx.store, record);\n}\n\nasync function remove(ctx: LocalAnswerContext, config: OfflineConfig, type: string): Promise<OfflineAnswer> {\n const id = ctx.params.id;\n const existing = await ctx.store.getRecord(type, id);\n if (!existing) return notOnDeviceAnswer(type, id);\n if (isRootWriteLocked(existing.rootId)) return needsConnectionAnswer(\"The root record is locked\");\n\n const base = existing.localOnly ? null : (existing.base ?? existing.resource);\n\n await ctx.store.transaction(async (store) => {\n const links = [...(await store.linksFrom(id)), ...(await store.linksTo(id))];\n for (const link of links) await store.deleteLink({ fromId: link.fromId, toId: link.toId, kind: link.kind });\n await store.deleteRecord(type, id);\n await store.enqueue({\n rootId: existing.rootId,\n method: \"DELETE\",\n path: queuePath(ctx),\n recordType: type,\n recordId: id,\n base,\n });\n const typeConfig = typeConfigOf(config, type);\n if (typeConfig?.afterLocalWrite) {\n await typeConfig.afterLocalWrite({\n store,\n module: typeConfig.module,\n id,\n method: \"DELETE\",\n resource: null,\n previous: existing.resource,\n });\n }\n });\n\n return { status: 204, body: undefined };\n}\n\n/** The request path as `EndpointCreator` built it, query string included. */\nexport function queuePath(ctx: Pick<LocalAnswerContext, \"request\">): string {\n const query = ctx.request.query.toString();\n return query ? `${ctx.request.path}?${query}` : ctx.request.path;\n}\n\n// ---------------------------------------------------------------------------------------------\n// The generic route list\n// ---------------------------------------------------------------------------------------------\n\nfunction readOnlyGuard(typeConfig: OfflineTypeConfig, answer: (ctx: LocalAnswerContext) => Promise<OfflineAnswer>) {\n return async (ctx: LocalAnswerContext): Promise<OfflineAnswer> =>\n typeConfig.readOnly ? needsConnectionAnswer(`${typeConfig.module.name} is read-only offline`) : answer(ctx);\n}\n\n/**\n * One set of routes per configured type, in matching order: the root record list before the\n * related list (both are `x/:id/<type>`), the related list last. These generic routes are not\n * queued by the layer: each write answer queues itself, with its base.\n */\nexport function buildGenericRoutes(config: OfflineConfig): OfflineRoute[] {\n const routes: OfflineRoute[] = [];\n const route = (method: OfflineMethod, pattern: OfflineRoute[\"pattern\"], answer: OfflineRoute[\"answer\"]) =>\n routes.push({ method, pattern, answer, queue: false });\n\n for (const typeConfig of config.types) {\n const type = typeConfig.module.name;\n route(\"GET\", [typeConfig.module, \":id\"], (ctx) => getOne(ctx, type));\n for (const kind of rootKinds(config)) {\n route(\"GET\", [kind.module, \":rootId\", typeConfig.module], (ctx) => rootList(ctx, kind, typeConfig));\n }\n route(\n \"POST\",\n [typeConfig.module],\n readOnlyGuard(typeConfig, (ctx) => create(ctx, config, type)),\n );\n route(\n \"PUT\",\n [typeConfig.module, \":id\"],\n readOnlyGuard(typeConfig, (ctx) => update(ctx, config, type)),\n );\n route(\n \"PATCH\",\n [typeConfig.module, \":id\"],\n readOnlyGuard(typeConfig, (ctx) => update(ctx, config, type)),\n );\n route(\n \"DELETE\",\n [typeConfig.module, \":id\"],\n readOnlyGuard(typeConfig, (ctx) => remove(ctx, config, type)),\n );\n }\n for (const typeConfig of config.types) {\n route(\"GET\", [\":parentType\", \":parentId\", typeConfig.module], (ctx) => relatedList(ctx, config, typeConfig));\n }\n\n return routes;\n}\n","import type { OfflineMethod, OfflineRoute, PatternSegment } from \"./types\";\n\nexport type RouteMatch = { route: OfflineRoute; params: Record<string, string> };\n\nfunction splitPath(path: string): string[] {\n const withoutQuery = path.split(\"?\")[0].split(\"#\")[0];\n return withoutQuery.split(\"/\").filter((segment) => segment.length > 0);\n}\n\n/** A Module segment may itself hold slashes (\"roots/played\"), so each one is expanded. */\nfunction expandPattern(pattern: PatternSegment[]): string[] {\n return pattern.flatMap((segment) => splitPath(typeof segment === \"string\" ? segment : segment.name));\n}\n\nexport function matchPattern(pattern: PatternSegment[], path: string): Record<string, string> | null {\n const expected = expandPattern(pattern);\n const actual = splitPath(path);\n if (expected.length !== actual.length) return null;\n\n const params: Record<string, string> = {};\n for (let index = 0; index < expected.length; index++) {\n const segment = expected[index];\n const value = decodeURIComponent(actual[index]);\n if (segment.startsWith(\":\")) {\n params[segment.slice(1)] = value;\n } else if (segment !== value) {\n return null;\n }\n }\n return params;\n}\n\n/** The first route, in the order given, whose method and pattern match. The query string is ignored. */\nexport function matchRoute(routes: OfflineRoute[], method: OfflineMethod, path: string): RouteMatch | null {\n for (const route of routes) {\n if (route.method !== method) continue;\n const params = matchPattern(route.pattern, path);\n if (params) return { route, params };\n }\n return null;\n}\n","import { getClientApiUrl } from \"../client/JsonApiClient\";\nimport type { ApiData } from \"../core/interfaces/ApiData\";\nimport { getApiUrl } from \"../unified/JsonApiRequest\";\nimport { getOfflineConfig, getOfflineStore, rootKinds } from \"./config\";\nimport {\n buildGenericRoutes,\n rootIdForResource,\n isRootWriteLocked,\n needsConnectionAnswer,\n queuePath,\n} from \"./generic-answers\";\nimport { matchRoute } from \"./router\";\nimport { setOfflineState } from \"./state\";\nimport type { DeviceStore } from \"./store/DeviceStore\";\nimport {\n NeedsConnectionError,\n type OfflineAnswer,\n type OfflineMethod,\n type OfflineRequest,\n type OfflineRoute,\n} from \"./types\";\n\nexport type LocalTransportRequest = {\n method: string;\n url: string;\n body?: any;\n files?: unknown;\n};\n\nconst METHODS: OfflineMethod[] = [\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\"];\n\nfunction apiBases(): string[] {\n const bases: string[] = [];\n for (const read of [getApiUrl, getClientApiUrl]) {\n try {\n const base = read();\n if (base) bases.push(base);\n } catch {\n // not configured on this side\n }\n }\n return bases;\n}\n\n/** The path relative to the API base, as `EndpointCreator` built it, and its query. */\nexport function splitApiUrl(url: string): { path: string; query: URLSearchParams } {\n let relative: string | undefined;\n for (const base of apiBases()) {\n if (url.startsWith(base)) {\n relative = url.slice(base.length);\n break;\n }\n }\n if (relative === undefined) {\n try {\n const parsed = new URL(url);\n relative = `${parsed.pathname}${parsed.search}`;\n } catch {\n relative = url;\n }\n }\n\n const [pathPart, ...queryParts] = relative.split(\"?\");\n return {\n path: pathPart.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\"),\n query: new URLSearchParams(queryParts.join(\"?\")),\n };\n}\n\nfunction toApiData(answer: OfflineAnswer): ApiData {\n const ok = answer.status >= 200 && answer.status < 300;\n return {\n ok,\n status: answer.status,\n statusText: ok ? \"OK\" : answer.status === 503 ? \"Service Unavailable\" : \"Error\",\n data: answer.body,\n };\n}\n\n/** The root record a custom write belongs to: a `<root>/:param` capture, a stored record named by a param, or the body. */\nasync function rootIdForCustomWrite(\n store: DeviceStore,\n pattern: OfflineRequest,\n params: Record<string, string>,\n rootSegmentParam: string | undefined,\n): Promise<string | undefined> {\n const config = getOfflineConfig();\n if (rootSegmentParam && params[rootSegmentParam]) return params[rootSegmentParam];\n\n for (const value of Object.values(params)) {\n for (const typeConfig of config.types) {\n const stored = await store.getRecord(typeConfig.module.name, value);\n if (stored?.rootId) return stored.rootId;\n }\n }\n return rootIdForResource(store, config, pattern.body?.data);\n}\n\nasync function refreshPendingCount(store: DeviceStore): Promise<void> {\n const entries = await store.queue();\n setOfflineState({ pending: entries.filter((entry) => entry.status !== \"conflict\").length });\n}\n\n/**\n * Answers a request from the device copy: the app's custom routes first, then the generic ones.\n * The result has the `ApiData` shape `directFetch` returns, so `translateResponse` and\n * `rehydrate()` run unchanged.\n */\nexport async function localTransport(request: LocalTransportRequest): Promise<ApiData> {\n try {\n const method = request.method.toUpperCase() as OfflineMethod;\n if (!METHODS.includes(method)) return toApiData(needsConnectionAnswer());\n if (request.files) return toApiData(needsConnectionAnswer(\"Uploading files needs a connection\"));\n\n const config = getOfflineConfig();\n const { path, query } = splitApiUrl(request.url);\n const offlineRequest: OfflineRequest = { method, path, query, body: request.body, url: request.url };\n\n const custom = matchRoute(config.routes, method, path);\n const match = custom ?? matchRoute(buildGenericRoutes(config), method, path);\n if (!match) return toApiData(needsConnectionAnswer(`${method} ${path} has no offline answer`));\n\n let store: DeviceStore;\n try {\n store = await getOfflineStore();\n } catch (error) {\n // The device copy cannot be opened here (another tab holds the file, storage refused,\n // no signed-in user): only the server can answer.\n if (error instanceof NeedsConnectionError) return toApiData(needsConnectionAnswer(error.message));\n console.warn(\"[offline] the device copy could not be opened\", error);\n return toApiData(needsConnectionAnswer(\"The device copy is not available in this tab\"));\n }\n const ctx = { request: offlineRequest, params: match.params, store };\n\n // The root record of a custom write (a `<root>/:param` capture of any root kind's module, a\n // stored record, or the body).\n const rootTypes = new Set(rootKinds(config).map((kind) => kind.module.name));\n const customRootId = async (route: OfflineRoute): Promise<string | undefined> => {\n const rootIndex = route.pattern.findIndex(\n (segment) => typeof segment !== \"string\" && rootTypes.has(segment.name),\n );\n const next = rootIndex >= 0 ? route.pattern[rootIndex + 1] : undefined;\n const rootParam = typeof next === \"string\" && next.startsWith(\":\") ? next.slice(1) : undefined;\n return rootIdForCustomWrite(store, offlineRequest, match.params, rootParam);\n };\n\n if (!custom || !custom.route.queue) {\n // A custom write that is not queued is refused on a locked root record too (GETs stay allowed).\n if (custom && method !== \"GET\") {\n const rootId = await customRootId(custom.route);\n if (rootId && isRootWriteLocked(rootId)) {\n return toApiData(needsConnectionAnswer(\"The root record is locked\"));\n }\n }\n const answer = await match.route.answer(ctx);\n if (method !== \"GET\") await refreshPendingCount(store);\n return toApiData(answer);\n }\n\n // A custom write the server must run too: refused on a locked root record, otherwise the answer\n // updates the device copy and the original request is queued in the same transaction.\n const rootId = await customRootId(custom.route);\n if (!rootId) return toApiData(needsConnectionAnswer(`${method} ${path} belongs to no root record on this device`));\n if (isRootWriteLocked(rootId)) return toApiData(needsConnectionAnswer(\"The root record is locked\"));\n\n const answer = await store.transaction(async (transactionStore) => {\n const result = await custom.route.answer({ ...ctx, store: transactionStore });\n if (result.status >= 200 && result.status < 300) {\n await transactionStore.enqueue({\n rootId,\n method,\n path: queuePath(ctx),\n body: request.body,\n base: null,\n });\n }\n return result;\n });\n await refreshPendingCount(store);\n return toApiData(answer);\n } catch (error) {\n if (error instanceof NeedsConnectionError) return toApiData(needsConnectionAnswer(error.message));\n console.error(\"[offline] local answer failed\", error);\n return toApiData({\n status: 500,\n body: {\n errors: [{ status: \"500\", title: \"Offline answer failed\", detail: String((error as Error)?.message ?? error) }],\n },\n });\n }\n}\n"]}
1
+ {"version":3,"sources":["/home/runner/work/nextjs-jsonapi/nextjs-jsonapi/dist/chunk-53SD4YRF.js","../src/offline/generic-answers.ts","../src/offline/router.ts","../src/offline/local-transport.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACF,sDAA4B;AAC5B;AACE;AACA;AACA;AACA;AACA;AACA;AACF,sDAA4B;AAC5B;AACE;AACF,sDAA4B;AAC5B;AACE;AACF,sDAA4B;AAC5B;AACA;ACLA,IAAM,kBAAA,EAAoB,EAAA;AAOnB,SAAS,WAAA,CAAY,MAAA,EAAgB,KAAA,EAAe,MAAA,EAAgB,IAAA,EAA8B;AACvG,EAAA,OAAO;AAAA,IACL,MAAA;AAAA,IACA,IAAA,EAAM,EAAE,MAAA,EAAQ,CAAC,EAAE,MAAA,EAAQ,MAAA,CAAO,MAAM,CAAA,EAAG,GAAI,KAAA,EAAO,EAAE,KAAK,EAAA,EAAI,CAAC,CAAA,EAAI,KAAA,EAAO,OAAO,CAAC,EAAE;AAAA,EACzF,CAAA;AACF;AALgB,qCAAA,WAAA,EAAA,aAAA,CAAA;AAOT,SAAS,qBAAA,CAAsB,OAAA,EAAiB,oBAAA,EAAqC;AAC1F,EAAA,OAAO,WAAA,CAAY,GAAA,EAAK,oBAAA,EAAsB,MAAA,EAAQ,kBAAkB,CAAA;AAC1E;AAFgB,qCAAA,qBAAA,EAAA,uBAAA,CAAA;AAIT,SAAS,cAAA,CAAe,MAAA,EAA+B;AAC5D,EAAA,OAAO,WAAA,CAAY,GAAA,EAAK,WAAA,EAAa,MAAM,CAAA;AAC7C;AAFgB,qCAAA,cAAA,EAAA,gBAAA,CAAA;AAKh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AAA;AACR,UAAA;AACP,QAAA;AACH,MAAA;AACO,MAAA;AACR,IAAA;AAC8B,IAAA;AACR,IAAA;AACT,EAAA;AAC6B,IAAA;AAC7B,IAAA;AACG,IAAA;AACP,MAAA;AACF,MAAA;AAC6B,QAAA;AACnC,MAAA;AACD,IAAA;AACH,EAAA;AACF;AAlFsB;AHmlB4B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/nextjs-jsonapi/nextjs-jsonapi/dist/chunk-53SD4YRF.js","sourcesContent":[null,"import { CURRENT_USER_STORAGE_KEY } from \"../features/user/data/user.storage\";\nimport { getOfflineConfig, rootKinds } from \"./config\";\nimport { getOfflineState } from \"./state\";\nimport type { DeviceStore, StoredLink, StoredRecord } from \"./store/DeviceStore\";\nimport type {\n LocalAnswerContext,\n OfflineAnswer,\n OfflineConfig,\n OfflineMethod,\n OfflineRootKind,\n OfflineRoute,\n OfflineTypeConfig,\n} from \"./types\";\n\nconst DEFAULT_PAGE_SIZE = 25;\n\n// ---------------------------------------------------------------------------------------------\n// Answers shared by every route\n// ---------------------------------------------------------------------------------------------\n\n/** A JSON:API errors document with one error, answered with `status`. */\nexport function errorAnswer(status: number, title: string, detail: string, code?: string): OfflineAnswer {\n return {\n status,\n body: { errors: [{ status: String(status), ...(code ? { code } : {}), title, detail }] },\n };\n}\n\nexport function needsConnectionAnswer(detail: string = \"Needs a connection\"): OfflineAnswer {\n return errorAnswer(503, \"Needs a connection\", detail, \"needs-connection\");\n}\n\nexport function notFoundAnswer(detail: string): OfflineAnswer {\n return errorAnswer(404, \"Not found\", detail);\n}\n\n/** A single document of one stored record, with `included` (`includedFor`). */\nexport async function singleAnswer(\n store: DeviceStore,\n record: StoredRecord,\n status: number = 200,\n): Promise<OfflineAnswer> {\n return { status, body: { data: record.resource, included: await includedFor(store, [record]) } };\n}\n\nexport function isRootWriteLocked(rootId: string | undefined): boolean {\n return !!rootId && getOfflineState().lockedRootIds.includes(rootId);\n}\n\n// ---------------------------------------------------------------------------------------------\n// Resource helpers\n// ---------------------------------------------------------------------------------------------\n\ntype ResourceIdentifier = { type: string; id: string };\n\nfunction identifiersOf(relationship: any): ResourceIdentifier[] {\n const data = relationship?.data;\n if (!data) return [];\n return (Array.isArray(data) ? data : [data]).filter((item: any) => item && item.type && item.id);\n}\n\nfunction linkedIds(links: StoredLink[], id: string): ResourceIdentifier[] {\n return links.map((link) =>\n link.fromId === id ? { type: link.toType, id: link.toId } : { type: link.fromType, id: link.fromId },\n );\n}\n\n/** Every stored resource linked to one of `ids`, in either direction, without duplicates or the records themselves. */\n/** The `{ type, id }` every relationship of a JSON:API resource points to. */\nfunction relationshipTargets(resource: any): { type: string; id: string }[] {\n const targets: { type: string; id: string }[] = [];\n for (const relationship of Object.values<any>(resource?.relationships ?? {})) {\n const data = relationship?.data;\n for (const ref of Array.isArray(data) ? data : data ? [data] : []) {\n if (ref?.type && ref?.id) targets.push({ type: ref.type, id: ref.id });\n }\n }\n return targets;\n}\n\n/**\n * The `included` of a local answer: the stored records linked to `records` (the synced links),\n * then the stored records their relationships point to, and one level further the stored records\n * the relationships of those included records point to (an NPC's root record, then the root record's\n * owner), so a model reads the same nested relationships it reads from the server.\n *\n * Stored resources point at each other (a root record at its owner, the owner at the root record's\n * company, the company back at the owner); `RehydrationFactory` skips a resource met again inside\n * its own chain, so those circles never recurse.\n */\nexport async function includedFor(store: DeviceStore, records: StoredRecord[]): Promise<any[]> {\n // 0: the answer's own records; 1: what they link to; 2: what those link to.\n const level = new Map<string, number>(records.map((record) => [`${record.type}:${record.id}`, 0]));\n const included: { resource: any; level: number }[] = [];\n\n const add = async (target: { type: string; id: string }, atLevel: number): Promise<void> => {\n const key = `${target.type}:${target.id}`;\n if (level.has(key)) return;\n level.set(key, atLevel);\n const stored = await store.getRecord(target.type, target.id);\n const resource = stored?.resource ?? signedInUserResource(target);\n if (resource) included.push({ resource, level: atLevel });\n };\n\n for (const record of records) {\n const links = [...(await store.linksFrom(record.id)), ...(await store.linksTo(record.id))];\n for (const target of linkedIds(links, record.id)) await add(target, 1);\n }\n for (const record of records) {\n for (const target of relationshipTargets(record.resource)) await add(target, 1);\n }\n for (const entry of included.filter((candidate) => candidate.level === 1)) {\n for (const target of relationshipTargets(entry.resource)) await add(target, 2);\n }\n return included.map((entry) => entry.resource);\n}\n\n/**\n * The signed-in user as a resource, when `target` is that user. Users are not kept on the device,\n * but a relationship to the signed-in user (every downloaded root record's owner) must still resolve:\n * the app tells a GM from a player by comparing the root record's owner with the signed-in user. The\n * resource comes from the copy CurrentUserProvider keeps in localStorage, without relationships.\n */\nfunction signedInUserResource(target: { type: string; id: string }): any | undefined {\n try {\n if (target.id !== getOfflineConfig().getUserId()) return undefined;\n const stored = JSON.parse(window.localStorage.getItem(CURRENT_USER_STORAGE_KEY) ?? \"null\");\n const user = stored?.jsonApi;\n if (user?.type !== target.type || user?.id !== target.id) return undefined;\n return { type: user.type, id: user.id, attributes: user.attributes ?? {}, meta: user.meta };\n } catch {\n return undefined;\n }\n}\n\nfunction attributeOf(record: StoredRecord, name: string): unknown {\n const value = record.resource?.attributes?.[name];\n if (value !== undefined && value !== null) return value;\n // The server value the sync keeps beside the resource.\n if (name === \"updatedAt\") return record.updatedAt ?? null;\n return value;\n}\n\n/** The server's default list order (`defineEntity` sets `defaultOrderBy: \"updatedAt DESC\"`). */\nexport const SERVER_DEFAULT_ORDER_BY = \"updatedAt DESC\";\n\n/** The only `orderBy` the server accepts (`buildLegacyOrderByClause`): one property, optional ASC/DESC. */\nconst ORDER_BY = /^([A-Za-z_][A-Za-z0-9_]*)(?:\\s+(ASC|DESC))?$/i;\n\nconst ISO_DATE = /^\\d{4}-\\d{2}-\\d{2}(T|$)/;\n\nfunction comparable(value: unknown): unknown {\n if (value instanceof Date) return value.getTime();\n if (typeof value === \"string\" && ISO_DATE.test(value)) {\n const time = Date.parse(value);\n if (!Number.isNaN(time)) return time;\n }\n return value;\n}\n\n/** Cypher ORDER BY on one property, ascending: null sorts after every value. */\nfunction compareAscending(left: unknown, right: unknown): number {\n const a = comparable(left);\n const b = comparable(right);\n const aNull = a === undefined || a === null;\n const bNull = b === undefined || b === null;\n if (aNull || bNull) return aNull === bNull ? 0 : aNull ? 1 : -1;\n if (typeof a === \"number\" && typeof b === \"number\") return a - b;\n if (typeof a === \"boolean\" && typeof b === \"boolean\") return Number(a) - Number(b);\n const x = String(a);\n const y = String(b);\n return x < y ? -1 : x > y ? 1 : 0;\n}\n\nexport type ListOptions = {\n /** The string attributes the server's fulltext index covers (default: every string attribute). */\n searchFields?: string[];\n /** The order with no `orderBy` (default `updatedAt DESC`, the server's). */\n defaultOrderBy?: string;\n};\n\n/**\n * `search` as the server runs it: the term is split into letter/digit tokens and a record\n * matches when every token appears, case-insensitive, inside one of its indexed string\n * attributes (the fulltext query `*token* AND ...`).\n */\nexport function searchRecords(\n records: StoredRecord[],\n query: URLSearchParams,\n options: ListOptions = {},\n): StoredRecord[] {\n const term = query.get(\"search\");\n if (term === null || term === undefined || term.trim() === \"\") return records;\n const tokens = term\n .toLowerCase()\n .split(/[^\\p{L}\\p{N}]+/u)\n .filter(Boolean);\n if (tokens.length === 0) return records;\n\n return records.filter((record) => {\n const attributes = record.resource?.attributes ?? {};\n const fields = options.searchFields ?? Object.keys(attributes);\n const texts = fields\n .map((field) => attributes[field])\n .filter((value): value is string => typeof value === \"string\")\n .map((value) => value.toLowerCase());\n return tokens.every((token) => texts.some((text) => text.includes(token)));\n });\n}\n\n/**\n * Orders records as the server's `ORDER BY` does for `orderBy` (`field` or `field ASC|DESC`),\n * or for the default order when there is none. `null` when the server would refuse the\n * `orderBy` (400).\n */\nexport function orderRecords(\n records: StoredRecord[],\n query: URLSearchParams,\n options: ListOptions = {},\n): StoredRecord[] | null {\n const requested = query.get(\"orderBy\")?.trim();\n const value = requested || options.defaultOrderBy?.trim() || SERVER_DEFAULT_ORDER_BY;\n const match = ORDER_BY.exec(value);\n if (!match) return null;\n const field = match[1];\n const desc = match[2]?.toUpperCase() === \"DESC\";\n return [...records].sort((left, right) => {\n const order = compareAscending(attributeOf(left, field), attributeOf(right, field));\n return desc ? -order : order;\n });\n}\n\nfunction linkUrl(base: string, query: URLSearchParams, changes: Record<string, string | undefined>): string {\n const params = new URLSearchParams(query);\n for (const [key, value] of Object.entries(changes)) {\n if (value === undefined) params.delete(key);\n else params.set(key, value);\n }\n const search = params.toString().replace(/%5B/g, \"[\").replace(/%5D/g, \"]\").replace(/%2C/g, \",\");\n return search ? `${base}?${search}` : base;\n}\n\n/**\n * One list answer for a set of stored records, as the server answers a list: `search`, then\n * `orderBy` (or the default order), then paged the way `JsonApiPaginator` pages (`fetchAll`,\n * `page[size]`, `page[offset]`), with `included`. App answers pass the records they selected.\n */\nexport async function listAnswer(\n ctx: LocalAnswerContext,\n records: StoredRecord[],\n options: ListOptions = {},\n): Promise<OfflineAnswer> {\n const { request, store } = ctx;\n const base = request.url ? request.url.split(\"?\")[0] : request.path;\n const sorted = orderRecords(searchRecords(records, request.query, options), request.query, options);\n if (!sorted) {\n return errorAnswer(400, \"Bad Request\", \"Invalid orderBy\");\n }\n\n if (request.query.get(\"fetchAll\") === \"true\") {\n return {\n status: 200,\n body: {\n data: sorted.map((record) => record.resource),\n included: await includedFor(store, sorted),\n links: { self: linkUrl(base, request.query, {}) },\n meta: { total: sorted.length },\n },\n };\n }\n\n const size = Number(request.query.get(\"page[size]\")) || DEFAULT_PAGE_SIZE;\n const offset = Number(request.query.get(\"page[offset]\")) || 0;\n const page = sorted.slice(offset, offset + size);\n\n const links: Record<string, string> = {\n self: linkUrl(base, request.query, { \"page[size]\": String(size), \"page[offset]\": undefined }),\n };\n if (offset + size < sorted.length) {\n links.next = linkUrl(base, request.query, { \"page[size]\": String(size), \"page[offset]\": String(offset + size) });\n }\n if (offset > 0) {\n links.prev = linkUrl(base, request.query, {\n \"page[size]\": String(size),\n \"page[offset]\": String(Math.max(0, offset - size)),\n });\n // The server names it `previous`; the client reads `prev`.\n links.previous = links.prev;\n }\n\n return {\n status: 200,\n body: {\n data: page.map((record) => record.resource),\n included: await includedFor(store, page),\n links,\n meta: { total: sorted.length },\n },\n };\n}\n\n/**\n * A list document of stored records in the order the caller settled, every record in one page,\n * with `included`: for an app's custom list query that has its own `ORDER BY` and no paging.\n */\nexport async function orderedListAnswer(store: DeviceStore, records: StoredRecord[]): Promise<OfflineAnswer> {\n return {\n status: 200,\n body: {\n data: records.map((record) => record.resource),\n included: await includedFor(store, records),\n meta: { total: records.length },\n },\n };\n}\n\n/**\n * A list document of resources the device computed rather than stored (a query-result\n * projection such as a search hit, built by its model), answered as they are, nothing included.\n */\nexport function resourceListAnswer(resources: any[]): OfflineAnswer {\n return { status: 200, body: { data: resources, included: [] } };\n}\n\nfunction listOptionsOf(typeConfig: OfflineTypeConfig): ListOptions {\n return { searchFields: typeConfig.searchFields, defaultOrderBy: typeConfig.defaultOrderBy };\n}\n\n// ---------------------------------------------------------------------------------------------\n// Link kinds\n// ---------------------------------------------------------------------------------------------\n\n/**\n * The kind a link written on the device carries for relationship `name`: the Neo4j type the\n * type config maps it to (the kind synced links carry), otherwise the name itself.\n */\nexport function linkKindFor(typeConfig: OfflineTypeConfig | undefined, name: string): string {\n return typeConfig?.relationshipKinds?.[name] ?? name;\n}\n\n/**\n * Every kind a link of relationship `name` may carry on the device: the name (written on the\n * device before a mapping existed) and the mapped Neo4j type (synced). `undefined` when the\n * Neo4j type is not known: then a link of any kind may be the one.\n */\nexport function linkKindsOf(typeConfig: OfflineTypeConfig | undefined, name: string): string[] | undefined {\n const mapped = typeConfig?.relationshipKinds?.[name];\n return mapped ? [name, mapped] : undefined;\n}\n\n/**\n * The stored links of `id` whose kind is one of `kinds` (Neo4j types and/or relationship\n * names). `out`: links from `id`; `in`: links to `id`; `both`: either.\n */\nexport async function linksOfKind(\n store: DeviceStore,\n id: string,\n kinds: string[],\n direction: \"out\" | \"in\" | \"both\" = \"both\",\n): Promise<StoredLink[]> {\n const result: StoredLink[] = [];\n const seen = new Set<string>();\n for (const kind of new Set(kinds)) {\n const links = [\n ...(direction !== \"in\" ? await store.linksFrom(id, kind) : []),\n ...(direction !== \"out\" ? await store.linksTo(id, kind) : []),\n ];\n for (const link of links) {\n const key = `${link.fromId}|${link.toId}|${link.kind}`;\n if (seen.has(key)) continue;\n seen.add(key);\n result.push(link);\n }\n }\n return result;\n}\n\nfunction typeConfigOf(config: OfflineConfig, type: string): OfflineTypeConfig | undefined {\n return config.types.find((typeConfig) => typeConfig.module.name === type);\n}\n\n/** The relationship names of `resource` that point to a record of `type`. */\nfunction relationshipNamesToward(resource: any, type: string): string[] {\n return Object.entries<any>(resource?.relationships ?? {})\n .filter(([, relationship]) => identifiersOf(relationship).some((identifier) => identifier.type === type))\n .map(([name]) => name);\n}\n\n// ---------------------------------------------------------------------------------------------\n// Reads\n// ---------------------------------------------------------------------------------------------\n\n/** A record that is not on the device: only the server can answer for it. */\nfunction notOnDeviceAnswer(type: string, id: string): OfflineAnswer {\n return needsConnectionAnswer(`${type} ${id} is not on this device`);\n}\n\nasync function getOne(ctx: LocalAnswerContext, type: string): Promise<OfflineAnswer> {\n const record = await ctx.store.getRecord(type, ctx.params.id);\n if (!record) return notOnDeviceAnswer(type, ctx.params.id);\n return singleAnswer(ctx.store, record);\n}\n\nasync function rootList(\n ctx: LocalAnswerContext,\n kind: OfflineRootKind,\n typeConfig: OfflineTypeConfig,\n): Promise<OfflineAnswer> {\n const rootType = kind.module.name;\n const rootId = ctx.params.rootId;\n if (!(await ctx.store.getRecord(rootType, rootId))) return notOnDeviceAnswer(rootType, rootId);\n const records = await ctx.store.listRecords({ type: typeConfig.module.name, rootId });\n return listAnswer(ctx, records, listOptionsOf(typeConfig));\n}\n\n/**\n * `GET <parent>/:parentId/<type>`: the stored records of `type` linked to the parent by the\n * relationship between the two types. That relationship is the one whose name, on either\n * record, points to the other type; its links are matched by name and by mapped Neo4j type.\n * When its Neo4j type is not known, links of any kind count.\n */\nasync function relatedList(\n ctx: LocalAnswerContext,\n config: OfflineConfig,\n typeConfig: OfflineTypeConfig,\n): Promise<OfflineAnswer> {\n const type = typeConfig.module.name;\n const { parentType, parentId } = ctx.params;\n const parent = await ctx.store.getRecord(parentType, parentId);\n if (!parent) return notOnDeviceAnswer(parentType, parentId);\n\n const links = [...(await ctx.store.linksFrom(parentId)), ...(await ctx.store.linksTo(parentId))].filter((link) =>\n link.fromId === parentId ? link.toType === type : link.fromType === type,\n );\n const candidates = await ctx.store.listRecords({\n type,\n ids: [...new Set(links.map((link) => (link.fromId === parentId ? link.toId : link.fromId)))],\n });\n\n const kinds = new Set<string>();\n let anyKind = false;\n const collect = (owner: OfflineTypeConfig | undefined, names: string[]) => {\n for (const name of names) {\n const known = linkKindsOf(owner, name);\n if (known) known.forEach((kind) => kinds.add(kind));\n else anyKind = true;\n }\n };\n collect(typeConfig, [\n ...new Set(candidates.flatMap((record) => relationshipNamesToward(record.resource, parentType))),\n ]);\n collect(typeConfigOf(config, parentType), relationshipNamesToward(parent.resource, type));\n\n const accepted = anyKind || kinds.size === 0 ? links : links.filter((link) => kinds.has(link.kind));\n const ids = new Set(accepted.map((link) => (link.fromId === parentId ? link.toId : link.fromId)));\n return listAnswer(\n ctx,\n candidates.filter((record) => ids.has(record.id)),\n listOptionsOf(typeConfig),\n );\n}\n\n// ---------------------------------------------------------------------------------------------\n// Writes\n// ---------------------------------------------------------------------------------------------\n\n/**\n * The root record a record belongs to: itself (the type of any root kind), a relationship to a\n * root of any kind, or a related stored record.\n */\nexport async function rootIdForResource(\n store: DeviceStore,\n config: OfflineConfig,\n resource: any,\n): Promise<string | undefined> {\n const rootTypes = new Set(rootKinds(config).map((kind) => kind.module.name));\n if (rootTypes.has(resource?.type) && resource.id) return resource.id;\n\n const identifiers = Object.values(resource?.relationships ?? {}).flatMap(identifiersOf);\n const root = identifiers.find((identifier) => rootTypes.has(identifier.type));\n if (root) return root.id;\n\n for (const identifier of identifiers) {\n const stored = await store.getRecord(identifier.type, identifier.id);\n if (stored?.rootId) return stored.rootId;\n }\n return undefined;\n}\n\nasync function linkRelationships(\n store: DeviceStore,\n typeConfig: OfflineTypeConfig | undefined,\n record: { type: string; id: string },\n before: Record<string, any>,\n after: Record<string, any>,\n): Promise<void> {\n for (const [name, relationship] of Object.entries(after)) {\n const previous = new Map(identifiersOf(before[name]).map((identifier) => [identifier.id, identifier]));\n const next = new Map(identifiersOf(relationship).map((identifier) => [identifier.id, identifier]));\n const kinds = linkKindsOf(typeConfig, name);\n\n for (const [id] of previous) {\n if (next.has(id)) continue;\n // Only the links of this relationship (by name or Neo4j type); any kind when it is not known.\n const links = kinds\n ? await linksOfKind(store, record.id, kinds, \"both\")\n : [...(await store.linksFrom(record.id)), ...(await store.linksTo(record.id))];\n for (const link of links) {\n if (link.fromId === id || link.toId === id) {\n await store.deleteLink({ fromId: link.fromId, toId: link.toId, kind: link.kind });\n }\n }\n }\n for (const [id, identifier] of next) {\n if (previous.has(id)) continue;\n await store.putLink({\n fromType: record.type,\n fromId: record.id,\n toType: identifier.type,\n toId: id,\n kind: linkKindFor(typeConfig, name),\n props: {},\n });\n }\n }\n}\n\n/** The `data` of a JSON:API document a model built (`createJsonApi()` or a dedicated method). */\nexport type ResourceDocumentData = {\n attributes?: Record<string, unknown>;\n relationships?: Record<string, unknown>;\n meta?: Record<string, unknown>;\n};\n\n/**\n * The resource a create document stands for, under `identity`: the document's attributes,\n * relationships and meta, as the device stores a record it creates.\n */\nexport function resourceFromDocument(document: any, identity: { type: string; id: string }): any {\n const data: ResourceDocumentData = document?.data ?? {};\n const resource: any = { type: identity.type, id: identity.id };\n if (data.attributes) resource.attributes = { ...data.attributes };\n if (data.relationships) resource.relationships = { ...data.relationships };\n if (data.meta) resource.meta = { ...data.meta };\n return resource;\n}\n\n/**\n * A stored resource with a document's `data` written over it: attributes and relationships merged\n * by name, and meta merged when the document carries one, as the device applies an edit.\n */\nexport function mergeResource(before: any, identity: { type: string; id: string }, data: ResourceDocumentData): any {\n const previous = before ?? identity;\n const resource: any = {\n ...previous,\n type: identity.type,\n id: identity.id,\n attributes: { ...(previous.attributes ?? {}), ...(data?.attributes ?? {}) },\n relationships: { ...(previous.relationships ?? {}), ...(data?.relationships ?? {}) },\n };\n if (data?.meta) resource.meta = { ...(previous.meta ?? {}), ...data.meta };\n return resource;\n}\n\nfunction newId(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") return crypto.randomUUID();\n return `local-${Date.now()}-${Math.random().toString(16).slice(2)}`;\n}\n\nasync function create(ctx: LocalAnswerContext, config: OfflineConfig, type: string): Promise<OfflineAnswer> {\n const typeConfig = typeConfigOf(config, type);\n const id: string = ctx.request.body?.data?.id ?? newId();\n const resource = resourceFromDocument(ctx.request.body, { type, id });\n const rootId = await rootIdForResource(ctx.store, config, resource);\n if (!rootId) return needsConnectionAnswer(`A new ${type} that belongs to no root record needs a connection`);\n if (isRootWriteLocked(rootId)) return needsConnectionAnswer(\"The root record is locked\");\n\n const record: StoredRecord = { type, id, rootId, resource, updatedAt: null, base: null, localOnly: true };\n await ctx.store.transaction(async (store) => {\n await store.putRecord(record);\n await linkRelationships(store, typeConfig, { type, id }, {}, resource.relationships ?? {});\n await store.enqueue({\n rootId,\n method: ctx.request.method,\n path: queuePath(ctx),\n body: ctx.request.body,\n base: null,\n });\n // The type's hook, inside the write's transaction: a throw rolls the write and the enqueue back.\n if (typeConfig?.afterLocalWrite) {\n await typeConfig.afterLocalWrite({\n store,\n module: typeConfig.module,\n id,\n method: \"POST\",\n resource,\n previous: null,\n });\n }\n });\n\n return singleAnswer(ctx.store, record, 201);\n}\n\nasync function update(ctx: LocalAnswerContext, config: OfflineConfig, type: string): Promise<OfflineAnswer> {\n const id = ctx.params.id;\n const existing = await ctx.store.getRecord(type, id);\n if (!existing) return notOnDeviceAnswer(type, id);\n if (isRootWriteLocked(existing.rootId)) return needsConnectionAnswer(\"The root record is locked\");\n\n const data = ctx.request.body?.data ?? {};\n const before = existing.resource ?? { type, id };\n const resource = mergeResource(before, { type, id }, data);\n // A record created on this device has no server version to merge against.\n const base = existing.localOnly ? null : (existing.base ?? before);\n\n const typeConfig = typeConfigOf(config, type);\n const method = ctx.request.method === \"PATCH\" ? \"PATCH\" : \"PUT\";\n const record: StoredRecord = { ...existing, resource, base, localOnly: existing.localOnly };\n await ctx.store.transaction(async (store) => {\n await store.putRecord(record);\n await linkRelationships(store, typeConfig, { type, id }, before.relationships ?? {}, data.relationships ?? {});\n await store.enqueue({\n rootId: existing.rootId,\n method: ctx.request.method,\n path: queuePath(ctx),\n body: ctx.request.body,\n recordType: type,\n recordId: id,\n base,\n });\n if (typeConfig?.afterLocalWrite) {\n await typeConfig.afterLocalWrite({ store, module: typeConfig.module, id, method, resource, previous: before });\n }\n });\n\n return singleAnswer(ctx.store, record);\n}\n\nasync function remove(ctx: LocalAnswerContext, config: OfflineConfig, type: string): Promise<OfflineAnswer> {\n const id = ctx.params.id;\n const existing = await ctx.store.getRecord(type, id);\n if (!existing) return notOnDeviceAnswer(type, id);\n if (isRootWriteLocked(existing.rootId)) return needsConnectionAnswer(\"The root record is locked\");\n\n const base = existing.localOnly ? null : (existing.base ?? existing.resource);\n\n await ctx.store.transaction(async (store) => {\n const links = [...(await store.linksFrom(id)), ...(await store.linksTo(id))];\n for (const link of links) await store.deleteLink({ fromId: link.fromId, toId: link.toId, kind: link.kind });\n await store.deleteRecord(type, id);\n await store.enqueue({\n rootId: existing.rootId,\n method: \"DELETE\",\n path: queuePath(ctx),\n recordType: type,\n recordId: id,\n base,\n });\n const typeConfig = typeConfigOf(config, type);\n if (typeConfig?.afterLocalWrite) {\n await typeConfig.afterLocalWrite({\n store,\n module: typeConfig.module,\n id,\n method: \"DELETE\",\n resource: null,\n previous: existing.resource,\n });\n }\n });\n\n return { status: 204, body: undefined };\n}\n\n/** The request path as `EndpointCreator` built it, query string included. */\nexport function queuePath(ctx: Pick<LocalAnswerContext, \"request\">): string {\n const query = ctx.request.query.toString();\n return query ? `${ctx.request.path}?${query}` : ctx.request.path;\n}\n\n// ---------------------------------------------------------------------------------------------\n// The generic route list\n// ---------------------------------------------------------------------------------------------\n\nfunction readOnlyGuard(typeConfig: OfflineTypeConfig, answer: (ctx: LocalAnswerContext) => Promise<OfflineAnswer>) {\n return async (ctx: LocalAnswerContext): Promise<OfflineAnswer> =>\n typeConfig.readOnly ? needsConnectionAnswer(`${typeConfig.module.name} is read-only offline`) : answer(ctx);\n}\n\n/**\n * One set of routes per configured type, in matching order: the root record list before the\n * related list (both are `x/:id/<type>`), the related list last. These generic routes are not\n * queued by the layer: each write answer queues itself, with its base.\n */\nexport function buildGenericRoutes(config: OfflineConfig): OfflineRoute[] {\n const routes: OfflineRoute[] = [];\n const route = (method: OfflineMethod, pattern: OfflineRoute[\"pattern\"], answer: OfflineRoute[\"answer\"]) =>\n routes.push({ method, pattern, answer, queue: false });\n\n for (const typeConfig of config.types) {\n const type = typeConfig.module.name;\n route(\"GET\", [typeConfig.module, \":id\"], (ctx) => getOne(ctx, type));\n for (const kind of rootKinds(config)) {\n route(\"GET\", [kind.module, \":rootId\", typeConfig.module], (ctx) => rootList(ctx, kind, typeConfig));\n }\n route(\n \"POST\",\n [typeConfig.module],\n readOnlyGuard(typeConfig, (ctx) => create(ctx, config, type)),\n );\n route(\n \"PUT\",\n [typeConfig.module, \":id\"],\n readOnlyGuard(typeConfig, (ctx) => update(ctx, config, type)),\n );\n route(\n \"PATCH\",\n [typeConfig.module, \":id\"],\n readOnlyGuard(typeConfig, (ctx) => update(ctx, config, type)),\n );\n route(\n \"DELETE\",\n [typeConfig.module, \":id\"],\n readOnlyGuard(typeConfig, (ctx) => remove(ctx, config, type)),\n );\n }\n for (const typeConfig of config.types) {\n route(\"GET\", [\":parentType\", \":parentId\", typeConfig.module], (ctx) => relatedList(ctx, config, typeConfig));\n }\n\n return routes;\n}\n","import type { OfflineMethod, OfflineRoute, PatternSegment } from \"./types\";\n\nexport type RouteMatch = { route: OfflineRoute; params: Record<string, string> };\n\nfunction splitPath(path: string): string[] {\n const withoutQuery = path.split(\"?\")[0].split(\"#\")[0];\n return withoutQuery.split(\"/\").filter((segment) => segment.length > 0);\n}\n\n/** A Module segment may itself hold slashes (\"roots/played\"), so each one is expanded. */\nfunction expandPattern(pattern: PatternSegment[]): string[] {\n return pattern.flatMap((segment) => splitPath(typeof segment === \"string\" ? segment : segment.name));\n}\n\nexport function matchPattern(pattern: PatternSegment[], path: string): Record<string, string> | null {\n const expected = expandPattern(pattern);\n const actual = splitPath(path);\n if (expected.length !== actual.length) return null;\n\n const params: Record<string, string> = {};\n for (let index = 0; index < expected.length; index++) {\n const segment = expected[index];\n const value = decodeURIComponent(actual[index]);\n if (segment.startsWith(\":\")) {\n params[segment.slice(1)] = value;\n } else if (segment !== value) {\n return null;\n }\n }\n return params;\n}\n\n/** The first route, in the order given, whose method and pattern match. The query string is ignored. */\nexport function matchRoute(routes: OfflineRoute[], method: OfflineMethod, path: string): RouteMatch | null {\n for (const route of routes) {\n if (route.method !== method) continue;\n const params = matchPattern(route.pattern, path);\n if (params) return { route, params };\n }\n return null;\n}\n","import { getClientApiUrl } from \"../client/JsonApiClient\";\nimport type { ApiData } from \"../core/interfaces/ApiData\";\nimport { getApiUrl } from \"../unified/JsonApiRequest\";\nimport { getOfflineConfig, getOfflineStore, rootKinds } from \"./config\";\nimport {\n buildGenericRoutes,\n rootIdForResource,\n isRootWriteLocked,\n needsConnectionAnswer,\n queuePath,\n} from \"./generic-answers\";\nimport { matchRoute } from \"./router\";\nimport { setOfflineState } from \"./state\";\nimport type { DeviceStore } from \"./store/DeviceStore\";\nimport {\n NeedsConnectionError,\n type OfflineAnswer,\n type OfflineMethod,\n type OfflineRequest,\n type OfflineRoute,\n} from \"./types\";\n\nexport type LocalTransportRequest = {\n method: string;\n url: string;\n body?: any;\n files?: unknown;\n};\n\nconst METHODS: OfflineMethod[] = [\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\"];\n\nfunction apiBases(): string[] {\n const bases: string[] = [];\n for (const read of [getApiUrl, getClientApiUrl]) {\n try {\n const base = read();\n if (base) bases.push(base);\n } catch {\n // not configured on this side\n }\n }\n return bases;\n}\n\n/** The path relative to the API base, as `EndpointCreator` built it, and its query. */\nexport function splitApiUrl(url: string): { path: string; query: URLSearchParams } {\n let relative: string | undefined;\n for (const base of apiBases()) {\n if (url.startsWith(base)) {\n relative = url.slice(base.length);\n break;\n }\n }\n if (relative === undefined) {\n try {\n const parsed = new URL(url);\n relative = `${parsed.pathname}${parsed.search}`;\n } catch {\n relative = url;\n }\n }\n\n const [pathPart, ...queryParts] = relative.split(\"?\");\n return {\n path: pathPart.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\"),\n query: new URLSearchParams(queryParts.join(\"?\")),\n };\n}\n\nfunction toApiData(answer: OfflineAnswer): ApiData {\n const ok = answer.status >= 200 && answer.status < 300;\n return {\n ok,\n status: answer.status,\n statusText: ok ? \"OK\" : answer.status === 503 ? \"Service Unavailable\" : \"Error\",\n data: answer.body,\n };\n}\n\n/** The root record a custom write belongs to: a `<root>/:param` capture, a stored record named by a param, or the body. */\nasync function rootIdForCustomWrite(\n store: DeviceStore,\n pattern: OfflineRequest,\n params: Record<string, string>,\n rootSegmentParam: string | undefined,\n): Promise<string | undefined> {\n const config = getOfflineConfig();\n if (rootSegmentParam && params[rootSegmentParam]) return params[rootSegmentParam];\n\n for (const value of Object.values(params)) {\n for (const typeConfig of config.types) {\n const stored = await store.getRecord(typeConfig.module.name, value);\n if (stored?.rootId) return stored.rootId;\n }\n }\n return rootIdForResource(store, config, pattern.body?.data);\n}\n\nasync function refreshPendingCount(store: DeviceStore): Promise<void> {\n const entries = await store.queue();\n setOfflineState({ pending: entries.filter((entry) => entry.status !== \"conflict\").length });\n}\n\n/**\n * Answers a request from the device copy: the app's custom routes first, then the generic ones.\n * The result has the `ApiData` shape `directFetch` returns, so `translateResponse` and\n * `rehydrate()` run unchanged.\n */\nexport async function localTransport(request: LocalTransportRequest): Promise<ApiData> {\n try {\n const method = request.method.toUpperCase() as OfflineMethod;\n if (!METHODS.includes(method)) return toApiData(needsConnectionAnswer());\n if (request.files) return toApiData(needsConnectionAnswer(\"Uploading files needs a connection\"));\n\n const config = getOfflineConfig();\n const { path, query } = splitApiUrl(request.url);\n const offlineRequest: OfflineRequest = { method, path, query, body: request.body, url: request.url };\n\n const custom = matchRoute(config.routes, method, path);\n const match = custom ?? matchRoute(buildGenericRoutes(config), method, path);\n if (!match) return toApiData(needsConnectionAnswer(`${method} ${path} has no offline answer`));\n\n let store: DeviceStore;\n try {\n store = await getOfflineStore();\n } catch (error) {\n // The device copy cannot be opened here (another tab holds the file, storage refused,\n // no signed-in user): only the server can answer.\n if (error instanceof NeedsConnectionError) return toApiData(needsConnectionAnswer(error.message));\n console.warn(\"[offline] the device copy could not be opened\", error);\n return toApiData(needsConnectionAnswer(\"The device copy is not available in this tab\"));\n }\n const ctx = { request: offlineRequest, params: match.params, store };\n\n // The root record of a custom write (a `<root>/:param` capture of any root kind's module, a\n // stored record, or the body).\n const rootTypes = new Set(rootKinds(config).map((kind) => kind.module.name));\n const customRootId = async (route: OfflineRoute): Promise<string | undefined> => {\n const rootIndex = route.pattern.findIndex(\n (segment) => typeof segment !== \"string\" && rootTypes.has(segment.name),\n );\n const next = rootIndex >= 0 ? route.pattern[rootIndex + 1] : undefined;\n const rootParam = typeof next === \"string\" && next.startsWith(\":\") ? next.slice(1) : undefined;\n return rootIdForCustomWrite(store, offlineRequest, match.params, rootParam);\n };\n\n if (!custom || !custom.route.queue) {\n // A custom write that is not queued is refused on a locked root record too (GETs stay allowed).\n if (custom && method !== \"GET\") {\n const rootId = await customRootId(custom.route);\n if (rootId && isRootWriteLocked(rootId)) {\n return toApiData(needsConnectionAnswer(\"The root record is locked\"));\n }\n }\n const answer = await match.route.answer(ctx);\n if (method !== \"GET\") await refreshPendingCount(store);\n return toApiData(answer);\n }\n\n // A custom write the server must run too: refused on a locked root record, otherwise the answer\n // updates the device copy and the original request is queued in the same transaction.\n const rootId = await customRootId(custom.route);\n if (!rootId) return toApiData(needsConnectionAnswer(`${method} ${path} belongs to no root record on this device`));\n if (isRootWriteLocked(rootId)) return toApiData(needsConnectionAnswer(\"The root record is locked\"));\n\n const answer = await store.transaction(async (transactionStore) => {\n const result = await custom.route.answer({ ...ctx, store: transactionStore });\n if (result.status >= 200 && result.status < 300) {\n await transactionStore.enqueue({\n rootId,\n method,\n path: queuePath(ctx),\n body: request.body,\n base: null,\n });\n }\n return result;\n });\n await refreshPendingCount(store);\n return toApiData(answer);\n } catch (error) {\n if (error instanceof NeedsConnectionError) return toApiData(needsConnectionAnswer(error.message));\n console.error(\"[offline] local answer failed\", error);\n return toApiData({\n status: 500,\n body: {\n errors: [{ status: \"500\", title: \"Offline answer failed\", detail: String((error as Error)?.message ?? error) }],\n },\n });\n }\n}\n"]}
@@ -4,7 +4,7 @@ import {
4
4
  import {
5
5
  VIEWPORT_COOKIE_NAME,
6
6
  checkPermissionsFromServer
7
- } from "./chunk-DPXOPLQP.mjs";
7
+ } from "./chunk-T6G2F2BK.mjs";
8
8
  import {
9
9
  __name
10
10
  } from "./chunk-PAWJFY3S.mjs";
@@ -138,4 +138,4 @@ export {
138
138
  ServerSession,
139
139
  buildOfflineManifest
140
140
  };
141
- //# sourceMappingURL=chunk-4RA5PRXX.mjs.map
141
+ //# sourceMappingURL=chunk-7OIWOPM5.mjs.map
@@ -21,7 +21,7 @@ async function directFetch(params) {
21
21
  return answerLocally(params);
22
22
  }
23
23
  if (offline && response.ok && params.method.toUpperCase() !== "GET") {
24
- const { writeThrough } = await Promise.resolve().then(() => _interopRequireWildcard(require("./write-through-BAPS24GL.js")));
24
+ const { writeThrough } = await Promise.resolve().then(() => _interopRequireWildcard(require("./write-through-HE2QSOVI.js")));
25
25
  await writeThrough({ method: params.method, url: params.url }, response);
26
26
  }
27
27
  return response;
@@ -33,7 +33,7 @@ function hasReplayHeader(headers) {
33
33
  }
34
34
  _chunk7QVYU63Ejs.__name.call(void 0, hasReplayHeader, "hasReplayHeader");
35
35
  async function answerLocally(params) {
36
- const { localTransport } = await Promise.resolve().then(() => _interopRequireWildcard(require("./local-transport-4YDJ6FQG.js")));
36
+ const { localTransport } = await Promise.resolve().then(() => _interopRequireWildcard(require("./local-transport-MJPOKPTU.js")));
37
37
  return localTransport({ method: params.method, url: params.url, body: params.body, files: params.files });
38
38
  }
39
39
  _chunk7QVYU63Ejs.__name.call(void 0, answerLocally, "answerLocally");
@@ -83,6 +83,9 @@ async function fetchFromApi(params) {
83
83
  if (requestBody !== void 0) {
84
84
  options.body = requestBody;
85
85
  }
86
+ if (params.credentials) {
87
+ options.credentials = params.credentials;
88
+ }
86
89
  if (params.token) {
87
90
  options.headers = { ...options.headers, Authorization: `Bearer ${params.token}` };
88
91
  }
@@ -110,4 +113,4 @@ _chunk7QVYU63Ejs.__name.call(void 0, fetchFromApi, "fetchFromApi");
110
113
 
111
114
 
112
115
  exports.directFetch = directFetch;
113
- //# sourceMappingURL=chunk-WCEYT3GG.js.map
116
+ //# sourceMappingURL=chunk-A5M3MORY.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/nextjs-jsonapi/nextjs-jsonapi/dist/chunk-A5M3MORY.js","../src/client/request.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACF,sDAA4B;AAC5B;AACE;AACF,sDAA4B;AAC5B;AACA;ACgBA,MAAA,SAAsB,WAAA,CAAY,MAAA,EAA6C;AAI7E,EAAA,MAAM,QAAA,EAAU,kDAAA,EAAoB,GAAK,CAAC,eAAA,CAAgB,MAAA,CAAO,iBAAiB,CAAA;AAClF,EAAA,GAAA,CAAI,QAAA,GAAW,CAAC,8CAAA,CAAgB,CAAE,OAAA,GAAU,CAAC,yDAAA,MAA2B,CAAO,MAAA,EAAQ,MAAA,CAAO,GAAG,CAAA,EAAG;AAClG,IAAA,OAAO,aAAA,CAAc,MAAM,CAAA;AAAA,EAC7B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,OAAA,CAAQ,QAAA,EAAU,EAAE,GAAG,OAAA,CAAQ,OAAA,EAAS,aAAA,EAAe,CAAA,OAAA,EAAU,MAAA,CAAO,KAAK,CAAA,EAAA;AAC/E,EAAA;AAEI,EAAA;AACiD,IAAA;AAEzB,IAAA;AACI,IAAA;AACI,IAAA;AAC9B,IAAA;AACqC,MAAA;AACjC,IAAA;AACU,MAAA;AAClB,IAAA;AACM,EAAA;AAIQ,IAAA;AACI,IAAA;AACI,IAAA;AACN,IAAA;AACQ,IAAA;AAC1B,EAAA;AAEO,EAAA;AACT;AAtFe;ADmDmE;AACA;AACA;AACA","file":"/home/runner/work/nextjs-jsonapi/nextjs-jsonapi/dist/chunk-A5M3MORY.js","sourcesContent":[null,"\"use client\";\n\nimport { ApiData } from \"../core/interfaces/ApiData\";\nimport { isOfflineConfigured } from \"../offline/config\";\nimport { getOfflineState, reachesNetworkWhileOffline, setOfflineState } from \"../offline/state\";\nimport { OFFLINE_REPLAY_HEADER } from \"../offline/types\";\n\nexport interface DirectFetchParams {\n method: string;\n url: string;\n token?: string;\n body?: any;\n files?: { [key: string]: File | Blob } | File | Blob;\n companyId?: string;\n language: string;\n additionalHeaders?: Record<string, string>;\n /**\n * Optional `fetch` credentials mode (e.g. \"include\" so the browser stores a cookie the API sets).\n * Omitted => no `credentials` option is passed, unchanged behaviour.\n */\n credentials?: RequestCredentials;\n}\n\n/**\n * Client-side direct fetch to bypass server action overhead.\n * Use this for client-side API calls.\n */\nexport async function directFetch(params: DirectFetchParams): Promise<ApiData> {\n // Offline mode is opt-in (`configureOffline`). Without it nothing below loads or runs. A request\n // the server runs as an offline replay always goes to the network, and so do the reads and the\n // change-set request of a reconnect attempt (the session stays offline until its sync succeeds).\n const offline = isOfflineConfigured() && !hasReplayHeader(params.additionalHeaders);\n if (offline && !getOfflineState().online && !reachesNetworkWhileOffline(params.method, params.url)) {\n return answerLocally(params);\n }\n\n const response = await fetchFromApi(params);\n\n if (offline && response.networkError) {\n setOfflineState({ online: false });\n return answerLocally(params);\n }\n if (offline && response.ok && params.method.toUpperCase() !== \"GET\") {\n const { writeThrough } = await import(\"../offline/write-through\");\n await writeThrough({ method: params.method, url: params.url }, response);\n }\n\n return response;\n}\n\nfunction hasReplayHeader(headers?: Record<string, string>): boolean {\n if (!headers) return false;\n return Object.keys(headers).some((key) => key.toLowerCase() === OFFLINE_REPLAY_HEADER);\n}\n\nasync function answerLocally(params: DirectFetchParams): Promise<ApiData> {\n const { localTransport } = await import(\"../offline/local-transport\");\n return localTransport({ method: params.method, url: params.url, body: params.body, files: params.files });\n}\n\nasync function fetchFromApi(params: DirectFetchParams): Promise<ApiData> {\n const response: ApiData = {\n data: undefined,\n ok: false,\n status: 0,\n statusText: \"\",\n };\n\n const additionalHeaders: Record<string, string> = { ...params.additionalHeaders };\n\n if (params.companyId) {\n additionalHeaders[\"x-companyid\"] = params.companyId;\n }\n additionalHeaders[\"x-language\"] = params.language;\n\n let requestBody: BodyInit | undefined = undefined;\n\n if (params.files) {\n const formData = new FormData();\n if (params.body && typeof params.body === \"object\") {\n for (const key in params.body) {\n if (Object.prototype.hasOwnProperty.call(params.body, key)) {\n formData.append(\n key,\n typeof params.body[key] === \"object\" ? JSON.stringify(params.body[key]) : params.body[key],\n );\n }\n }\n }\n\n if (params.files instanceof Blob) {\n formData.append(\"file\", params.files);\n } else if (typeof params.files === \"object\" && params.files !== null) {\n for (const key in params.files) {\n if (Object.prototype.hasOwnProperty.call(params.files, key)) {\n formData.append(key, params.files[key]);\n }\n }\n }\n\n requestBody = formData;\n } else if (params.body !== undefined) {\n requestBody = JSON.stringify(params.body);\n additionalHeaders[\"Content-Type\"] = \"application/json\";\n }\n\n const options: RequestInit = {\n method: params.method,\n headers: { Accept: \"application/json\", ...additionalHeaders },\n };\n\n if (requestBody !== undefined) {\n options.body = requestBody;\n }\n\n if (params.credentials) {\n options.credentials = params.credentials;\n }\n\n if (params.token) {\n options.headers = { ...options.headers, Authorization: `Bearer ${params.token}` };\n }\n\n try {\n const apiResponse = await fetch(params.url, options);\n\n response.ok = apiResponse.ok;\n response.status = apiResponse.status;\n response.statusText = apiResponse.statusText;\n try {\n response.data = await apiResponse.json();\n } catch {\n response.data = undefined;\n }\n } catch {\n // fetch() only throws when the API could not be reached at all (server\n // down, DNS, connection refused). Report it as 503 so consumers can tell\n // \"API unreachable\" apart from a 500 the API actually returned.\n response.ok = false;\n response.status = 503;\n response.statusText = \"Service Unavailable\";\n response.data = undefined;\n response.networkError = true;\n }\n\n return response;\n}\n"]}
@@ -1,12 +1,12 @@
1
1
  import {
2
2
  directFetch
3
- } from "./chunk-M3N7LPHX.mjs";
3
+ } from "./chunk-S7SPAC6X.mjs";
4
4
  import {
5
5
  ENV,
6
6
  JsonApiDataFactory,
7
7
  setBootstrapper,
8
8
  translateResponse
9
- } from "./chunk-MQ7TXALH.mjs";
9
+ } from "./chunk-YMCL3JXZ.mjs";
10
10
  import {
11
11
  getClientToken
12
12
  } from "./chunk-AUXK7QSA.mjs";
@@ -78,7 +78,8 @@ async function ClientJsonApiGet(params) {
78
78
  token,
79
79
  companyId: params.companyId,
80
80
  language: params.language,
81
- additionalHeaders: _clientConfig?.additionalHeaders
81
+ additionalHeaders: _clientConfig?.additionalHeaders,
82
+ credentials: params.credentials
82
83
  });
83
84
  return translateResponse({
84
85
  classKey: params.classKey,
@@ -112,7 +113,8 @@ async function ClientJsonApiPost(params) {
112
113
  files: params.files,
113
114
  companyId: params.companyId,
114
115
  language: params.language,
115
- additionalHeaders: _clientConfig?.additionalHeaders
116
+ additionalHeaders: _clientConfig?.additionalHeaders,
117
+ credentials: params.credentials
116
118
  });
117
119
  return translateResponse({
118
120
  classKey: params.responseType ?? params.classKey,
@@ -139,7 +141,8 @@ async function ClientJsonApiPut(params) {
139
141
  files: params.files,
140
142
  companyId: params.companyId,
141
143
  language: params.language,
142
- additionalHeaders: _clientConfig?.additionalHeaders
144
+ additionalHeaders: _clientConfig?.additionalHeaders,
145
+ credentials: params.credentials
143
146
  });
144
147
  return translateResponse({
145
148
  classKey: params.responseType ?? params.classKey,
@@ -166,7 +169,8 @@ async function ClientJsonApiPatch(params) {
166
169
  files: params.files,
167
170
  companyId: params.companyId,
168
171
  language: params.language,
169
- additionalHeaders: _clientConfig?.additionalHeaders
172
+ additionalHeaders: _clientConfig?.additionalHeaders,
173
+ credentials: params.credentials
170
174
  });
171
175
  return translateResponse({
172
176
  classKey: params.responseType ?? params.classKey,
@@ -185,7 +189,8 @@ async function ClientJsonApiDelete(params) {
185
189
  token,
186
190
  companyId: params.companyId,
187
191
  language: params.language,
188
- additionalHeaders: _clientConfig?.additionalHeaders
192
+ additionalHeaders: _clientConfig?.additionalHeaders,
193
+ credentials: params.credentials
189
194
  });
190
195
  return translateResponse({
191
196
  classKey: params.responseType ?? params.classKey,
@@ -209,4 +214,4 @@ export {
209
214
  ClientJsonApiPatch,
210
215
  ClientJsonApiDelete
211
216
  };
212
- //# sourceMappingURL=chunk-AUD6ZLBB.mjs.map
217
+ //# sourceMappingURL=chunk-BE6UMM5X.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/features/user/data/user.storage.ts","../src/client/JsonApiClient.ts"],"sourcesContent":["/**\n * localStorage key backing the `CurrentUserProvider` atom.\n *\n * Owned by this library, not by the apps that consume it: `<Logout />` clears\n * it on every sign-out. Kept in its own module so both the provider that writes\n * it and the component that clears it can reference the same constant without\n * importing each other.\n */\nexport const CURRENT_USER_STORAGE_KEY = \"user\";\n","\"use client\";\n\nimport { ENV } from \"../core/env\";\nimport { JsonApiDataFactory } from \"../core/factories/JsonApiDataFactory\";\nimport { ApiRequestDataTypeInterface } from \"../core/interfaces/ApiRequestDataTypeInterface\";\nimport { ApiResponseInterface } from \"../core/interfaces/ApiResponseInterface\";\nimport { setBootstrapper } from \"../core/registry/bootstrapStore\";\nimport { translateResponse } from \"../core/utils/translateResponse\";\nimport { ModuleWithPermissions } from \"../permissions/types\";\nimport { directFetch } from \"./request\";\nimport { getClientToken } from \"./token\";\n\n// Config storage for client contexts\nlet _clientConfig: {\n apiUrl: string;\n appUrl?: string;\n trackablePages?: ModuleWithPermissions[];\n bootstrapper?: () => void;\n additionalHeaders?: Record<string, string>;\n} | null = null;\n\n/**\n * Configure the JSON:API client for browser contexts.\n * Call this in your client-side initialization or use JsonApiProvider.\n */\nexport function configureClientJsonApi(config: {\n apiUrl: string;\n appUrl?: string;\n trackablePages?: ModuleWithPermissions[];\n bootstrapper?: () => void;\n additionalHeaders?: Record<string, string>;\n}): void {\n _clientConfig = config;\n if (config.bootstrapper) {\n setBootstrapper(config.bootstrapper);\n config.bootstrapper();\n }\n}\n\nexport function getClientApiUrl(): string {\n if (_clientConfig?.apiUrl) {\n return _clientConfig.apiUrl;\n }\n const envUrl = ENV.API_URL;\n if (!envUrl) {\n throw new Error(\n \"API URL not configured. Use configureClientJsonApi() or set NEXT_PUBLIC_API_URL environment variable.\",\n );\n }\n return envUrl;\n}\n\nexport function getClientAppUrl(): string {\n if (_clientConfig?.appUrl) {\n return _clientConfig.appUrl;\n }\n const envUrl = ENV.APP_URL;\n if (!envUrl) {\n throw new Error(\n \"App URL not configured. Use configureClientJsonApi({ appUrl }) or set NEXT_PUBLIC_ADDRESS environment variable.\",\n );\n }\n return envUrl.trim().replace(/\\/+$/, \"\");\n}\n\nexport function getClientTrackablePages(): ModuleWithPermissions[] {\n return _clientConfig?.trackablePages ?? [];\n}\n\nfunction runClientBootstrapper(): void {\n if (_clientConfig?.bootstrapper) {\n _clientConfig.bootstrapper();\n }\n}\n\n/**\n * Resolve the final request URL for an endpoint (client-side variant of `buildUrl`\n * in `unified/JsonApiRequest.ts` — kept in lockstep with it).\n *\n * - `endpoint` starting with \"http\" is always passed through unchanged (existing behaviour).\n * - Otherwise, an explicit `baseUrl` (per-call override) takes precedence over the global\n * `getClientApiUrl()` resolution. Omitting `baseUrl` preserves today's behaviour exactly.\n */\nexport function buildClientUrl(endpoint: string, baseUrl?: string): string {\n if (endpoint.startsWith(\"http\")) return endpoint;\n const apiUrl = baseUrl ?? getClientApiUrl();\n return `${apiUrl}${endpoint}`;\n}\n\nexport async function ClientJsonApiGet(params: {\n classKey: ApiRequestDataTypeInterface;\n endpoint: string;\n companyId?: string;\n language: string;\n baseUrl?: string;\n credentials?: RequestCredentials;\n}): Promise<ApiResponseInterface> {\n runClientBootstrapper();\n const token = await getClientToken();\n\n const apiResponse = await directFetch({\n method: \"GET\",\n url: buildClientUrl(params.endpoint, params.baseUrl),\n token,\n companyId: params.companyId,\n language: params.language,\n additionalHeaders: _clientConfig?.additionalHeaders,\n credentials: params.credentials,\n });\n\n return translateResponse({\n classKey: params.classKey,\n apiResponse,\n companyId: params.companyId,\n language: params.language,\n paginationHandler: async (endpoint: string) =>\n ClientJsonApiGet({\n classKey: params.classKey,\n endpoint,\n companyId: params.companyId,\n language: params.language,\n baseUrl: params.baseUrl,\n }),\n });\n}\n\nexport async function ClientJsonApiPost(params: {\n classKey: ApiRequestDataTypeInterface;\n endpoint: string;\n companyId?: string;\n body?: any;\n overridesJsonApiCreation?: boolean;\n files?: { [key: string]: File | Blob } | File | Blob;\n language: string;\n responseType?: ApiRequestDataTypeInterface;\n baseUrl?: string;\n credentials?: RequestCredentials;\n}): Promise<ApiResponseInterface> {\n runClientBootstrapper();\n const token = await getClientToken();\n\n let body = params.body;\n if (!body) {\n body = {};\n } else if (params.overridesJsonApiCreation !== true) {\n body = JsonApiDataFactory.create(params.classKey, body);\n }\n\n const apiResponse = await directFetch({\n method: \"POST\",\n url: buildClientUrl(params.endpoint, params.baseUrl),\n token,\n body,\n files: params.files,\n companyId: params.companyId,\n language: params.language,\n additionalHeaders: _clientConfig?.additionalHeaders,\n credentials: params.credentials,\n });\n\n return translateResponse({\n classKey: params.responseType ?? params.classKey,\n apiResponse,\n companyId: params.companyId,\n language: params.language,\n });\n}\n\nexport async function ClientJsonApiPut(params: {\n classKey: ApiRequestDataTypeInterface;\n endpoint: string;\n companyId?: string;\n body?: any;\n files?: { [key: string]: File | Blob } | File | Blob;\n language: string;\n responseType?: ApiRequestDataTypeInterface;\n baseUrl?: string;\n credentials?: RequestCredentials;\n}): Promise<ApiResponseInterface> {\n runClientBootstrapper();\n const token = await getClientToken();\n\n let body = params.body;\n if (!body) {\n body = {};\n } else {\n body = JsonApiDataFactory.create(params.classKey, body);\n }\n\n const apiResponse = await directFetch({\n method: \"PUT\",\n url: buildClientUrl(params.endpoint, params.baseUrl),\n token,\n body,\n files: params.files,\n companyId: params.companyId,\n language: params.language,\n additionalHeaders: _clientConfig?.additionalHeaders,\n credentials: params.credentials,\n });\n\n return translateResponse({\n classKey: params.responseType ?? params.classKey,\n apiResponse,\n companyId: params.companyId,\n language: params.language,\n });\n}\n\nexport async function ClientJsonApiPatch(params: {\n classKey: ApiRequestDataTypeInterface;\n endpoint: string;\n companyId?: string;\n body?: any;\n files?: { [key: string]: File | Blob } | File | Blob;\n overridesJsonApiCreation?: boolean;\n responseType?: ApiRequestDataTypeInterface;\n language: string;\n baseUrl?: string;\n credentials?: RequestCredentials;\n}): Promise<ApiResponseInterface> {\n runClientBootstrapper();\n const token = await getClientToken();\n\n let body = params.body;\n if (!body) {\n body = {};\n } else if (params.overridesJsonApiCreation !== true) {\n body = JsonApiDataFactory.create(params.classKey, body);\n }\n\n const apiResponse = await directFetch({\n method: \"PATCH\",\n url: buildClientUrl(params.endpoint, params.baseUrl),\n token,\n body,\n files: params.files,\n companyId: params.companyId,\n language: params.language,\n additionalHeaders: _clientConfig?.additionalHeaders,\n credentials: params.credentials,\n });\n\n return translateResponse({\n classKey: params.responseType ?? params.classKey,\n apiResponse,\n companyId: params.companyId,\n language: params.language,\n });\n}\n\nexport async function ClientJsonApiDelete(params: {\n classKey: ApiRequestDataTypeInterface;\n endpoint: string;\n companyId?: string;\n language: string;\n responseType?: ApiRequestDataTypeInterface;\n baseUrl?: string;\n credentials?: RequestCredentials;\n}): Promise<ApiResponseInterface> {\n runClientBootstrapper();\n const token = await getClientToken();\n\n const apiResponse = await directFetch({\n method: \"DELETE\",\n url: buildClientUrl(params.endpoint, params.baseUrl),\n token,\n companyId: params.companyId,\n language: params.language,\n additionalHeaders: _clientConfig?.additionalHeaders,\n credentials: params.credentials,\n });\n\n return translateResponse({\n classKey: params.responseType ?? params.classKey,\n apiResponse,\n companyId: params.companyId,\n language: params.language,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAQO,IAAM,2BAA2B;;;ACKxC,IAAI,gBAMO;AAMJ,SAAS,uBAAuB,QAM9B;AACP,kBAAgB;AAChB,MAAI,OAAO,cAAc;AACvB,oBAAgB,OAAO,YAAY;AACnC,WAAO,aAAa;AAAA,EACtB;AACF;AAZgB;AAcT,SAAS,kBAA0B;AACxC,MAAI,eAAe,QAAQ;AACzB,WAAO,cAAc;AAAA,EACvB;AACA,QAAM,SAAS,IAAI;AACnB,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;AAXgB;AAaT,SAAS,kBAA0B;AACxC,MAAI,eAAe,QAAQ;AACzB,WAAO,cAAc;AAAA,EACvB;AACA,QAAM,SAAS,IAAI;AACnB,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,SAAO,OAAO,KAAK,EAAE,QAAQ,QAAQ,EAAE;AACzC;AAXgB;AAaT,SAAS,0BAAmD;AACjE,SAAO,eAAe,kBAAkB,CAAC;AAC3C;AAFgB;AAIhB,SAAS,wBAA8B;AACrC,MAAI,eAAe,cAAc;AAC/B,kBAAc,aAAa;AAAA,EAC7B;AACF;AAJS;AAcF,SAAS,eAAe,UAAkB,SAA0B;AACzE,MAAI,SAAS,WAAW,MAAM,EAAG,QAAO;AACxC,QAAM,SAAS,WAAW,gBAAgB;AAC1C,SAAO,GAAG,MAAM,GAAG,QAAQ;AAC7B;AAJgB;AAMhB,eAAsB,iBAAiB,QAOL;AAChC,wBAAsB;AACtB,QAAM,QAAQ,MAAM,eAAe;AAEnC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