@seedprotocol/sdk 0.7.4 → 0.7.5-next.871.g8788c94

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 (135) hide show
  1. package/README.md +99 -0
  2. package/dist/{BasePathResolver-DrzGVH9L.js → BasePathResolver-B-fK7_N_.js} +142 -8
  3. package/dist/BasePathResolver-B-fK7_N_.js.map +1 -0
  4. package/dist/{ClientManager-Dfu4jcgm.js → ClientManager-C7VkO5Hg.js} +342 -206
  5. package/dist/ClientManager-C7VkO5Hg.js.map +1 -0
  6. package/dist/{Item-BUUFuywT.js → Item-BDmsdNTQ.js} +234 -163
  7. package/dist/Item-BDmsdNTQ.js.map +1 -0
  8. package/dist/{ModelProperty-B6cnRvIz.js → ModelProperty-Cqw6yn7y.js} +37 -37
  9. package/dist/{ModelProperty-B6cnRvIz.js.map → ModelProperty-Cqw6yn7y.js.map} +1 -1
  10. package/dist/{Schema-Bf-jOLq0.js → Schema-BJLYOUgp.js} +57 -37
  11. package/dist/Schema-BJLYOUgp.js.map +1 -0
  12. package/dist/{SchemaValidationService-BNYMacsx.js → SchemaValidationService-CzybXLiS.js} +6 -6
  13. package/dist/{SchemaValidationService-BNYMacsx.js.map → SchemaValidationService-CzybXLiS.js.map} +1 -1
  14. package/dist/{backfillMetadataPropertyIds-C2-s_jUa.js → backfillMetadataPropertyIds-DAsETfD_.js} +3 -3
  15. package/dist/{backfillMetadataPropertyIds-C2-s_jUa.js.map → backfillMetadataPropertyIds-DAsETfD_.js.map} +1 -1
  16. package/dist/{configurePlatform-BzfirKuM.js → configurePlatform-CFQF_i1T.js} +2 -2
  17. package/dist/{configurePlatform-BzfirKuM.js.map → configurePlatform-CFQF_i1T.js.map} +1 -1
  18. package/dist/{detachRowsBeforeDelete-B0Daoz9Z.js → detachRowsBeforeDelete-D4gxxk46.js} +2 -2
  19. package/dist/{detachRowsBeforeDelete-B0Daoz9Z.js.map → detachRowsBeforeDelete-D4gxxk46.js.map} +1 -1
  20. package/dist/discardNewDraft-g8w3uHFM.js +78 -0
  21. package/dist/discardNewDraft-g8w3uHFM.js.map +1 -0
  22. package/dist/{eas-Dq5Kx_Nd.js → eas-BcXZ2hIn.js} +25 -12
  23. package/dist/eas-BcXZ2hIn.js.map +1 -0
  24. package/dist/{errors-DdWbxb_n.js → errors-CCMxedOB.js} +43 -38
  25. package/dist/errors-CCMxedOB.js.map +1 -0
  26. package/dist/{getItem-9bYSErSj.js → getItem-BUs1Xa48.js} +4 -4
  27. package/dist/{getItem-9bYSErSj.js.map → getItem-BUs1Xa48.js.map} +1 -1
  28. package/dist/{getPublishPayload-DPy-uMrR.js → getPublishPayload-CwNOhnir.js} +25 -15
  29. package/dist/getPublishPayload-CwNOhnir.js.map +1 -0
  30. package/dist/{getPublishUploads-J-143iSV.js → getPublishUploads-pEOrXJbF.js} +506 -45
  31. package/dist/getPublishUploads-pEOrXJbF.js.map +1 -0
  32. package/dist/{index-7y2f_iQz.js → index-BQSK-r_A.js} +2 -2
  33. package/dist/index-BQSK-r_A.js.map +1 -0
  34. package/dist/{index-C61Rxy0F.js → index-zAs84LDi.js} +8 -8
  35. package/dist/index-zAs84LDi.js.map +1 -0
  36. package/dist/{index.browser-C1pisOEa.js → index.browser-irwaBIj0.js} +11 -11
  37. package/dist/{index.browser-C1pisOEa.js.map → index.browser-irwaBIj0.js.map} +1 -1
  38. package/dist/{index.node-BAlST8pD.js → index.node-BYkndQN7.js} +6 -6
  39. package/dist/{index.node-BAlST8pD.js.map → index.node-BYkndQN7.js.map} +1 -1
  40. package/dist/main.js +91 -504
  41. package/dist/main.js.map +1 -1
  42. package/dist/{mimeTypes-DHAHC4eZ.js → mimeTypes-C9r76DCH.js} +7 -2
  43. package/dist/{mimeTypes-DHAHC4eZ.js.map → mimeTypes-C9r76DCH.js.map} +1 -1
  44. package/dist/node.js +10 -10
  45. package/dist/platform.browser.js +6 -6
  46. package/dist/platform.node.js +4 -4
  47. package/dist/{property-zFPMtR3T.js → property-5AD2naVS.js} +7 -7
  48. package/dist/{property-zFPMtR3T.js.map → property-5AD2naVS.js.map} +1 -1
  49. package/dist/{propertyValidationRules-CeFVhdQg.js → propertyValidationRules-Bdgz0Nrr.js} +10 -10
  50. package/dist/{propertyValidationRules-CeFVhdQg.js.map → propertyValidationRules-Bdgz0Nrr.js.map} +1 -1
  51. package/dist/{publishDraftGraph-CuVq6iAR.js → publishDraftGraph-DGhC9ifI.js} +6 -6
  52. package/dist/{publishDraftGraph-CuVq6iAR.js.map → publishDraftGraph-DGhC9ifI.js.map} +1 -1
  53. package/dist/{resetAmbiguousLegacyItemData-DsFTnMBz.js → resetAmbiguousLegacyItemData-HSB77N9c.js} +2 -2
  54. package/dist/{resetAmbiguousLegacyItemData-DsFTnMBz.js.map → resetAmbiguousLegacyItemData-HSB77N9c.js.map} +1 -1
  55. package/dist/{resolveModelForSyncedSeed-RUsgAZXG.js → resolveModelForSyncedSeed-CAKAJgr6.js} +2 -2
  56. package/dist/{resolveModelForSyncedSeed-RUsgAZXG.js.map → resolveModelForSyncedSeed-CAKAJgr6.js.map} +1 -1
  57. package/dist/src/Item/Item.d.ts +4 -1
  58. package/dist/src/Item/Item.d.ts.map +1 -1
  59. package/dist/src/Item/errors.d.ts +3 -1
  60. package/dist/src/Item/errors.d.ts.map +1 -1
  61. package/dist/src/ItemProperty/service/actors/saveValueToDb/saveItemStorage.d.ts.map +1 -1
  62. package/dist/src/Model/Model.d.ts +2 -1
  63. package/dist/src/Model/Model.d.ts.map +1 -1
  64. package/dist/src/Schema/Schema.d.ts.map +1 -1
  65. package/dist/src/Schema/service/schemaMachine.d.ts +3 -0
  66. package/dist/src/Schema/service/schemaMachine.d.ts.map +1 -1
  67. package/dist/src/client/clientManagerMachine.d.ts.map +1 -1
  68. package/dist/src/db/alignRowPublishers.d.ts +25 -0
  69. package/dist/src/db/alignRowPublishers.d.ts.map +1 -0
  70. package/dist/src/db/canonicalizeModelTypes.d.ts +2 -2
  71. package/dist/src/db/canonicalizeModelTypes.d.ts.map +1 -1
  72. package/dist/src/db/read/getModelSchemas.d.ts +3 -2
  73. package/dist/src/db/read/getModelSchemas.d.ts.map +1 -1
  74. package/dist/src/db/read/getPublishPayload.d.ts.map +1 -1
  75. package/dist/src/db/read/getPublishUploads.d.ts.map +1 -1
  76. package/dist/src/db/read/getSchemaUidForModel.d.ts.map +1 -1
  77. package/dist/src/db/read/getSeedPublisher.d.ts +7 -0
  78. package/dist/src/db/read/getSeedPublisher.d.ts.map +1 -0
  79. package/dist/src/db/read/nameMatchLevels.d.ts +64 -0
  80. package/dist/src/db/read/nameMatchLevels.d.ts.map +1 -0
  81. package/dist/src/db/read/resolveModelRecord.d.ts.map +1 -1
  82. package/dist/src/db/read/summarizePublishWork.d.ts +2 -0
  83. package/dist/src/db/read/summarizePublishWork.d.ts.map +1 -1
  84. package/dist/src/db/write/applyArweaveL1TransactionIdLocal.d.ts +5 -3
  85. package/dist/src/db/write/applyArweaveL1TransactionIdLocal.d.ts.map +1 -1
  86. package/dist/src/db/write/claimUnpublishedDrafts.d.ts +4 -2
  87. package/dist/src/db/write/claimUnpublishedDrafts.d.ts.map +1 -1
  88. package/dist/src/db/write/createMetadata.d.ts.map +1 -1
  89. package/dist/src/db/write/createNewItem.d.ts.map +1 -1
  90. package/dist/src/db/write/createSeed.d.ts.map +1 -1
  91. package/dist/src/db/write/createVersion.d.ts.map +1 -1
  92. package/dist/src/db/write/discardNewDraft.d.ts +8 -0
  93. package/dist/src/db/write/discardNewDraft.d.ts.map +1 -0
  94. package/dist/src/db/write/restoreDataItemIdsOverwrittenByL1.d.ts +18 -0
  95. package/dist/src/db/write/restoreDataItemIdsOverwrittenByL1.d.ts.map +1 -0
  96. package/dist/src/db/write/updateItemPropertyValue.d.ts.map +1 -1
  97. package/dist/src/eas.d.ts.map +1 -1
  98. package/dist/src/events/item/syncDbWithEas.d.ts.map +1 -1
  99. package/dist/src/helpers/constants.d.ts.map +1 -1
  100. package/dist/src/helpers/db.d.ts.map +1 -1
  101. package/dist/src/helpers/easValueTypes.d.ts +16 -0
  102. package/dist/src/helpers/easValueTypes.d.ts.map +1 -0
  103. package/dist/src/helpers/htmlEmbeddedDataUriPublish.d.ts +13 -2
  104. package/dist/src/helpers/htmlEmbeddedDataUriPublish.d.ts.map +1 -1
  105. package/dist/src/helpers/ownership.d.ts +9 -12
  106. package/dist/src/helpers/ownership.d.ts.map +1 -1
  107. package/dist/src/helpers/publishConfig.d.ts +9 -4
  108. package/dist/src/helpers/publishConfig.d.ts.map +1 -1
  109. package/dist/src/imports/index.d.ts +1 -1
  110. package/dist/src/imports/index.d.ts.map +1 -1
  111. package/dist/src/imports/json.d.ts.map +1 -1
  112. package/dist/src/index.d.ts +2 -1
  113. package/dist/src/index.d.ts.map +1 -1
  114. package/dist/src/types/import.d.ts +20 -0
  115. package/dist/src/types/import.d.ts.map +1 -1
  116. package/dist/{syncDbWithEas-CRpnkq00.js → syncDbWithEas-BmJXqfgN.js} +92 -22
  117. package/dist/syncDbWithEas-BmJXqfgN.js.map +1 -0
  118. package/dist/{tabEvents-nBUq_1u1.js → tabEvents-DXun7vdK.js} +4 -4
  119. package/dist/{tabEvents-nBUq_1u1.js.map → tabEvents-DXun7vdK.js.map} +1 -1
  120. package/dist/{tolerantWebAccess-DIt3R8_u.js → tolerantWebAccess-DXxgX2x7.js} +7 -7
  121. package/dist/{tolerantWebAccess-DIt3R8_u.js.map → tolerantWebAccess-DXxgX2x7.js.map} +1 -1
  122. package/dist/{updateSeedRevokedAt-DtTPSzpM.js → updateSeedRevokedAt-DkLSDwUX.js} +3 -3
  123. package/dist/{updateSeedRevokedAt-DtTPSzpM.js.map → updateSeedRevokedAt-DkLSDwUX.js.map} +1 -1
  124. package/package.json +9 -5
  125. package/dist/BasePathResolver-DrzGVH9L.js.map +0 -1
  126. package/dist/ClientManager-Dfu4jcgm.js.map +0 -1
  127. package/dist/Item-BUUFuywT.js.map +0 -1
  128. package/dist/Schema-Bf-jOLq0.js.map +0 -1
  129. package/dist/eas-Dq5Kx_Nd.js.map +0 -1
  130. package/dist/errors-DdWbxb_n.js.map +0 -1
  131. package/dist/getPublishPayload-DPy-uMrR.js.map +0 -1
  132. package/dist/getPublishUploads-J-143iSV.js.map +0 -1
  133. package/dist/index-7y2f_iQz.js.map +0 -1
  134. package/dist/index-C61Rxy0F.js.map +0 -1
  135. package/dist/syncDbWithEas-CRpnkq00.js.map +0 -1
@@ -1,28 +1,499 @@
1
- import { N as resolveSeedIdsFromRefString, O as normalizeRelationPropertyValue, Q as isPublishedSeedRef, i as isDataType, M as ModelPropertyDataTypes, R as getStorageDirForDataType, J as BaseFileManager, E as BaseDb, o as htmlEmbeddedImageCoPublish, S as getContentSha256, U as buildArweaveContentTags, V as getItemStorageSubdir, W as getItemStorageLocalFileName, m as metadata } from './BasePathResolver-DrzGVH9L.js';
1
+ import { h as BaseFileManager, M as ModelPropertyDataTypes, B as BaseDb, p as htmlEmbeddedImageCoPublish, Z as getArweaveUrlForTransaction, W as resolveSeedIdsFromRefString, V as normalizeRelationPropertyValue, _ as INTERNAL_STORAGE_MODEL_FILE_IDS, U as isPublishedSeedRef, i as isDataType, $ as getStorageDirForDataType, a0 as getContentSha256, a1 as buildArweaveContentTags, a2 as getItemStorageSubdir, a3 as getItemStorageLocalFileName, m as metadata } from './BasePathResolver-B-fK7_N_.js';
2
2
  import { BaseArweaveClient } from '@seedprotocol/arweave';
3
- import { g as getPublishDraftGraph, a as getSegmentedItemProperties } from './publishDraftGraph-CuVq6iAR.js';
3
+ import { g as getPublishDraftGraph, a as getSegmentedItemProperties } from './publishDraftGraph-DGhC9ifI.js';
4
4
  import debug from 'debug';
5
- import { I as Item, c as compareMetadataRowsLatestFirst } from './Item-BUUFuywT.js';
5
+ import { I as Item, d as waitForEntityIdle, e as compareMetadataRowsLatestFirst } from './Item-BDmsdNTQ.js';
6
+ import { parseFragment } from 'parse5';
6
7
  import { eq, and } from 'drizzle-orm';
8
+ import { a as getContentHash, b as isVerbatimItemStorageDraftRow, c as convertVerbatimItemStorageRow } from './ClientManager-C7VkO5Hg.js';
7
9
  import 'pluralize';
8
10
  import '@seedprotocol/eas';
9
- import { r as resolveUploadMimeType } from './mimeTypes-DHAHC4eZ.js';
10
- import { i as isVerbatimItemStorageDraftRow, c as convertVerbatimItemStorageRow } from './ClientManager-Dfu4jcgm.js';
11
- import 'xstate';
12
- import '@sinclair/typebox';
13
- import 'drizzle-orm/sqlite-core';
14
- import 'nanoid';
15
- import 'nanoid-dictionary';
16
- import '@seedprotocol/query';
17
- import '@noble/hashes/sha256';
18
- import '@noble/hashes/sha3';
19
- import '@noble/hashes/utils';
20
- import 'lodash-es';
21
- import './errors-DdWbxb_n.js';
22
- import './model-oHA3YhOd.js';
23
- import './property-zFPMtR3T.js';
24
- import 'rxjs';
25
- import './tabEvents-nBUq_1u1.js';
11
+ import { g as getExtensionForMimeType, r as resolveUploadMimeType } from './mimeTypes-C9r76DCH.js';
12
+
13
+ const HTML_EMBEDDED_MAX_IMAGES_PER_DOC = 50;
14
+ const HTML_EMBEDDED_MAX_IMAGE_BYTES = 5 * 1024 * 1024;
15
+ const HTML_EMBEDDED_MAX_TOTAL_BYTES = 25 * 1024 * 1024;
16
+ const DATA_URI_IMAGE = /^data:(image\/[a-zA-Z0-9.+-]+);base64,([\s\S]*)$/i;
17
+ const MIME_NORMALIZE = {
18
+ 'image/jpg': 'image/jpeg',
19
+ };
20
+ function normalizeMime(m) {
21
+ const lower = m.toLowerCase().trim();
22
+ return MIME_NORMALIZE[lower] ?? lower;
23
+ }
24
+ const ALLOWED_MIMES = new Set([
25
+ 'image/png',
26
+ 'image/jpeg',
27
+ 'image/webp',
28
+ 'image/gif',
29
+ 'image/svg+xml',
30
+ ]);
31
+ class HtmlEmbeddedDataUriLimitError extends Error {
32
+ constructor(message) {
33
+ super(message);
34
+ this.name = 'HtmlEmbeddedDataUriLimitError';
35
+ }
36
+ }
37
+ function resolveEffectiveHtmlEmbeddedDataUriPolicy(propertyDef, publishLevel) {
38
+ const fromProp = propertyDef?.htmlEmbeddedDataUriPolicy;
39
+ if (fromProp === 'materialize' || fromProp === 'preserve')
40
+ return fromProp;
41
+ if (publishLevel === 'materialize' || publishLevel === 'preserve')
42
+ return publishLevel;
43
+ return 'materialize';
44
+ }
45
+ function getAttr(node, name) {
46
+ const a = node.attrs?.find((x) => x.name === name);
47
+ return a?.value;
48
+ }
49
+ /**
50
+ * Walk fragment tree; collect unique data:image base64 URIs with limits.
51
+ */
52
+ async function extractDataUriImagesFromHtml(html) {
53
+ const fragment = parseFragment(html);
54
+ const found = [];
55
+ const seenUris = new Set();
56
+ let totalBytes = 0;
57
+ const walk = async (node) => {
58
+ if (node.nodeName === '#text' || node.nodeName === '#comment')
59
+ return;
60
+ const el = node;
61
+ if (el.tagName === 'img') {
62
+ const src = getAttr(el, 'src')?.trim();
63
+ if (src && src.startsWith('data:image/')) {
64
+ const m = DATA_URI_IMAGE.exec(src);
65
+ if (m) {
66
+ const mimeRaw = normalizeMime(m[1]);
67
+ if (!ALLOWED_MIMES.has(mimeRaw)) {
68
+ throw new HtmlEmbeddedDataUriLimitError(`Unsupported embedded image type: ${mimeRaw}. Allowed: ${[...ALLOWED_MIMES].join(', ')}`);
69
+ }
70
+ let binary;
71
+ try {
72
+ const b64 = m[2].replace(/\s/g, '');
73
+ binary = Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
74
+ }
75
+ catch {
76
+ throw new HtmlEmbeddedDataUriLimitError('Invalid base64 in embedded image data URI');
77
+ }
78
+ const byteLength = binary.byteLength;
79
+ if (byteLength > HTML_EMBEDDED_MAX_IMAGE_BYTES) {
80
+ throw new HtmlEmbeddedDataUriLimitError(`Embedded image exceeds max size (${HTML_EMBEDDED_MAX_IMAGE_BYTES} bytes)`);
81
+ }
82
+ totalBytes += byteLength;
83
+ if (totalBytes > HTML_EMBEDDED_MAX_TOTAL_BYTES) {
84
+ throw new HtmlEmbeddedDataUriLimitError(`Total embedded image size exceeds max (${HTML_EMBEDDED_MAX_TOTAL_BYTES} bytes)`);
85
+ }
86
+ if (!seenUris.has(src)) {
87
+ if (seenUris.size >= HTML_EMBEDDED_MAX_IMAGES_PER_DOC) {
88
+ throw new HtmlEmbeddedDataUriLimitError(`Too many distinct embedded images (max ${HTML_EMBEDDED_MAX_IMAGES_PER_DOC})`);
89
+ }
90
+ seenUris.add(src);
91
+ const stableKey = await getContentHash(binary);
92
+ found.push({ dataUri: src, stableKey, byteLength, mimeType: mimeRaw, bytes: binary });
93
+ }
94
+ }
95
+ }
96
+ }
97
+ const parent = el;
98
+ if (parent.childNodes) {
99
+ for (const c of parent.childNodes)
100
+ await walk(c);
101
+ }
102
+ };
103
+ for (const c of fragment.childNodes)
104
+ await walk(c);
105
+ return found;
106
+ }
107
+ function escapeAttributeValue(value) {
108
+ return value.replace(/&/g, '&').replace(/"/g, '"');
109
+ }
110
+ /**
111
+ * Rewrite attribute values of `html` by splicing each new value into the original string: every
112
+ * byte other than the rewritten attributes stays as written. Re-serializing the parsed tree would
113
+ * not round-trip (parse5 drops the newline the parser eats after `<pre>`/`<textarea>`/`<listing>`,
114
+ * a fragment parse drops doctype/html/head/body, and quoting, case and line endings are normalized),
115
+ * and sealed Html must not change with the serializer.
116
+ *
117
+ * `rewrite` gets each attribute's (entity-decoded) value and returns its new value, or undefined to
118
+ * leave it. A rewritten attribute is written as `name="value"`.
119
+ */
120
+ function rewriteHtmlAttributes(html, rewrite) {
121
+ const fragment = parseFragment(html, { sourceCodeLocationInfo: true });
122
+ const edits = [];
123
+ const walk = (node) => {
124
+ if (node.nodeName === '#text' || node.nodeName === '#comment')
125
+ return;
126
+ const el = node;
127
+ if (el.attrs?.length) {
128
+ for (const attr of el.attrs) {
129
+ if (attr.prefix)
130
+ continue;
131
+ const next = rewrite(el, attr.name, attr.value);
132
+ const location = el.sourceCodeLocation?.attrs?.[attr.name];
133
+ if (next === undefined || !location)
134
+ continue;
135
+ edits.push({
136
+ start: location.startOffset,
137
+ end: location.endOffset,
138
+ text: `${attr.name}="${escapeAttributeValue(next)}"`,
139
+ });
140
+ }
141
+ }
142
+ const parent = el;
143
+ if (parent.childNodes) {
144
+ for (const c of parent.childNodes)
145
+ walk(c);
146
+ }
147
+ };
148
+ for (const c of fragment.childNodes)
149
+ walk(c);
150
+ let out = html;
151
+ for (const edit of edits.sort((a, b) => b.start - a.start)) {
152
+ out = out.slice(0, edit.start) + edit.text + out.slice(edit.end);
153
+ }
154
+ return out;
155
+ }
156
+ /**
157
+ * Replace `data:image/...` `<img src>` values with Arweave URLs (keyed by data URI). Only those
158
+ * `src` attributes change; the rest of the Html is kept byte for byte.
159
+ */
160
+ function replaceDataUrisInParsedHtml(html, replacements) {
161
+ if (replacements.size === 0)
162
+ return html;
163
+ return rewriteHtmlAttributes(html, (el, attrName, value) => {
164
+ if (el.tagName !== 'img' || attrName !== 'src')
165
+ return undefined;
166
+ return replacements.get(value.trim());
167
+ });
168
+ }
169
+ /**
170
+ * `seed:property/<propertyName>` in Html stands for the Arweave URL of the same item's
171
+ * `<propertyName>` storage property (Image, File or Json). Publish uploads that property first,
172
+ * then rewrites the placeholder to its gateway URL before the Html is uploaded, so Html can show a
173
+ * file published alongside it without embedding it (e.g. `<img class="u-featured"
174
+ * src="seed:property/featureImage">`).
175
+ */
176
+ const SEED_PROPERTY_REF_PREFIX = 'seed:property/';
177
+ const SEED_PROPERTY_REF = /^seed:property\/([A-Za-z_$][A-Za-z0-9_$]*)$/;
178
+ /** Attributes whose whole (trimmed) value may be a `seed:property/` placeholder. */
179
+ const SEED_PROPERTY_REF_ATTRIBUTES = new Set(['src', 'href', 'poster']);
180
+ const seedPropertyRefName = (attrName, value) => SEED_PROPERTY_REF_ATTRIBUTES.has(attrName) ? SEED_PROPERTY_REF.exec(value.trim())?.[1] : undefined;
181
+ /** A `seed:property/` placeholder that names no usable property, or whose upload is unknown. */
182
+ class HtmlSeedPropertyRefError extends Error {
183
+ constructor(message) {
184
+ super(message);
185
+ this.name = 'HtmlSeedPropertyRefError';
186
+ }
187
+ }
188
+ /** Property names referenced by `seed:property/<name>` placeholders in `html`, each once. */
189
+ function findSeedPropertyRefsInHtml(html) {
190
+ if (!html.includes(SEED_PROPERTY_REF_PREFIX))
191
+ return [];
192
+ const names = new Set();
193
+ rewriteHtmlAttributes(html, (_el, attrName, value) => {
194
+ const name = seedPropertyRefName(attrName, value);
195
+ if (name)
196
+ names.add(name);
197
+ return undefined;
198
+ });
199
+ return [...names];
200
+ }
201
+ /** Replace `seed:property/<name>` placeholders with `urlByPropertyName.get(name)`; other bytes are kept. */
202
+ function replaceSeedPropertyRefsInHtml(html, urlByPropertyName) {
203
+ if (urlByPropertyName.size === 0)
204
+ return html;
205
+ return rewriteHtmlAttributes(html, (_el, attrName, value) => {
206
+ const name = seedPropertyRefName(attrName, value);
207
+ return name ? urlByPropertyName.get(name) : undefined;
208
+ });
209
+ }
210
+ const SEED_PROPERTY_REF_DATA_TYPES = [
211
+ ModelPropertyDataTypes.Image,
212
+ ModelPropertyDataTypes.File,
213
+ ModelPropertyDataTypes.Json,
214
+ ];
215
+ /**
216
+ * The storage property of `item` a `seed:property/<name>` placeholder names, and the seed it holds.
217
+ * Html properties are refused: an Html seed may itself be deferred to after the rewrite.
218
+ */
219
+ function resolveSeedPropertyRefTarget(item, propertyName) {
220
+ const property = item.properties.find((p) => p.propertyName === propertyName || p.propertyName === `${propertyName}Id`);
221
+ const def = property?.propertyDef;
222
+ if (!property || !def) {
223
+ throw new HtmlSeedPropertyRefError(`Html references ${SEED_PROPERTY_REF_PREFIX}${propertyName}, but ${item.modelName} has no property ${propertyName}`);
224
+ }
225
+ const dataType = normalizeDataTypeLocal(def.dataType);
226
+ const storageType = dataType === ModelPropertyDataTypes.Relation ? normalizeDataTypeLocal(def.refValueType) : dataType;
227
+ if (!SEED_PROPERTY_REF_DATA_TYPES.includes(storageType)) {
228
+ throw new HtmlSeedPropertyRefError(`Html references ${SEED_PROPERTY_REF_PREFIX}${propertyName}, but ${propertyName} is ${def.dataType}; ` +
229
+ `only Image, File and Json properties can be referenced`);
230
+ }
231
+ const snap = property.getService().getSnapshot();
232
+ const ctx = 'context' in snap ? snap.context : null;
233
+ const ids = resolveSeedIdsFromRefString(normalizeRelationPropertyValue(ctx?.propertyValue) ?? '');
234
+ if (!ids.seedLocalId && !ids.seedUid) {
235
+ throw new HtmlSeedPropertyRefError(`Html references ${SEED_PROPERTY_REF_PREFIX}${propertyName}, but ${propertyName} has no value`);
236
+ }
237
+ return ids;
238
+ }
239
+ const ARWEAVE_TX_ID = /^[a-z0-9_-]{43}$/i;
240
+ /**
241
+ * The Arweave tx of the storage seed a placeholder names: uploaded in this publish's phase 1, or,
242
+ * when not uploaded now, the transaction it was published with (its storageTransactionId).
243
+ */
244
+ async function resolveSeedPropertyRefTxId(item, propertyName, txBySeedLocalId) {
245
+ const { seedLocalId, seedUid } = resolveSeedPropertyRefTarget(item, propertyName);
246
+ const uploaded = seedLocalId ? txBySeedLocalId.get(seedLocalId) : undefined;
247
+ if (uploaded)
248
+ return uploaded;
249
+ const storageItem = await Item.find({ seedLocalId, seedUid });
250
+ const st = storageItem?.internalProperties['storageTransactionId'] ??
251
+ storageItem?.allProperties['storageTransactionId'];
252
+ const stSnap = st?.getService().getSnapshot();
253
+ const stValue = stSnap && 'context' in stSnap ? stSnap.context.propertyValue : undefined;
254
+ if (typeof stValue === 'string' && ARWEAVE_TX_ID.test(stValue.trim()))
255
+ return stValue.trim();
256
+ throw new HtmlSeedPropertyRefError(`Html references ${SEED_PROPERTY_REF_PREFIX}${propertyName}, but ${propertyName} was not uploaded ` +
257
+ `in this publish and has no published transaction`);
258
+ }
259
+ async function deleteCoPublishRowsForParent(appDb, parentSeedLocalId) {
260
+ if (!appDb)
261
+ return;
262
+ await appDb.delete(htmlEmbeddedImageCoPublish).where(eq(htmlEmbeddedImageCoPublish.parentSeedLocalId, parentSeedLocalId));
263
+ }
264
+ /**
265
+ * Name of the file holding an embedded image's bytes in the images folder: `<imageSeedLocalId>.<ext>`,
266
+ * the extension following the image's MIME type (one of {@link ALLOWED_MIMES}).
267
+ */
268
+ function embeddedImageFileName(imageSeedLocalId, mimeType) {
269
+ return `${imageSeedLocalId}.${getExtensionForMimeType(mimeType) ?? 'bin'}`;
270
+ }
271
+ /** Path of the file {@link createImageItemFromBytes} wrote for an Image seed, or undefined if there is none. */
272
+ async function findEmbeddedImageFilePath(imageSeedLocalId) {
273
+ for (const mimeType of ALLOWED_MIMES) {
274
+ const filePath = BaseFileManager.getFilesPath('images', embeddedImageFileName(imageSeedLocalId, mimeType));
275
+ if (await BaseFileManager.pathExists(filePath))
276
+ return filePath;
277
+ }
278
+ return undefined;
279
+ }
280
+ /**
281
+ * Create an Image item for an embedded image and write its bytes to the images folder, where publish
282
+ * reads them for upload ({@link findEmbeddedImageFilePath}). Its storageTransactionId stays empty
283
+ * until the upload writes the transaction id, as for any other storage seed.
284
+ */
285
+ async function createImageItemFromBytes(bytes, mimeType) {
286
+ const imageItem = await Item.create({
287
+ modelName: 'Image',
288
+ modelFileId: INTERNAL_STORAGE_MODEL_FILE_IDS.image,
289
+ });
290
+ await waitForEntityIdle(imageItem, { timeout: 60000 });
291
+ const filePath = BaseFileManager.getFilesPath('images', embeddedImageFileName(imageItem.seedLocalId, mimeType));
292
+ await BaseFileManager.createDirIfNotExists(BaseFileManager.getFilesPath('images'));
293
+ const data = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
294
+ try {
295
+ await BaseFileManager.saveFile(filePath, data);
296
+ }
297
+ catch {
298
+ const fs = await BaseFileManager.getFs();
299
+ fs.writeFileSync(filePath, bytes);
300
+ }
301
+ return { seedLocalId: imageItem.seedLocalId };
302
+ }
303
+ /**
304
+ * Scan Html storage properties, materialize embedded images as Image items, insert co-publish rows.
305
+ * Call before phase-1 Arweave tx build. Does not rewrite Html files yet.
306
+ */
307
+ async function prepareHtmlEmbeddedImagesForPublish(item, publishPolicy) {
308
+ const appDb = BaseDb.getAppDb();
309
+ if (!appDb) {
310
+ return { deferredHtmlSeedLocalIds: [] };
311
+ }
312
+ const deferred = new Set();
313
+ // The item's own Html, and the Html of the draft items published with it: each gets its embedded
314
+ // images materialized and co-published (rows keyed by the item owning the Html property).
315
+ for (const parent of [item, ...(await getRelatedDraftsCoPublishedWith(item))]) {
316
+ await prepareHtmlEmbeddedImagesOfItem(appDb, parent, publishPolicy, deferred);
317
+ }
318
+ return { deferredHtmlSeedLocalIds: [...deferred] };
319
+ }
320
+ /**
321
+ * Draft items (no seed uid yet) that a publish of `item` publishes with it: every draft reachable
322
+ * through relation and list properties, as getPublishPayload and getPublishUploads walk them
323
+ * (publishDraftGraph.ts). Html-embedded images of these items are co-published with `item` like its own.
324
+ */
325
+ async function getRelatedDraftsCoPublishedWith(item) {
326
+ const _mod_0 = await import('./publishDraftGraph-DGhC9ifI.js');
327
+ const _ns_0 = _mod_0.p;
328
+ const { getPublishDraftGraph } = _ns_0;
329
+ const { drafts } = await getPublishDraftGraph(item);
330
+ return drafts.map((d) => d.item);
331
+ }
332
+ async function prepareHtmlEmbeddedImagesOfItem(appDb, item, publishPolicy, deferred) {
333
+ await deleteCoPublishRowsForParent(appDb, item.seedLocalId);
334
+ for (const p of item.properties) {
335
+ const def = p.propertyDef;
336
+ if (!def || normalizeDataTypeLocal(def.dataType) !== ModelPropertyDataTypes.Html)
337
+ continue;
338
+ const snap = p.getService().getSnapshot();
339
+ const ctx = 'context' in snap ? snap.context : null;
340
+ const htmlSeedLocalId = typeof ctx?.propertyValue === 'string' ? ctx.propertyValue : '';
341
+ const refResolved = ctx?.refResolvedValue;
342
+ if (!htmlSeedLocalId?.trim() || !refResolved)
343
+ continue;
344
+ const filePath = `${BaseFileManager.getFilesPath('html')}/${refResolved}`;
345
+ const exists = await BaseFileManager.pathExists(filePath);
346
+ if (!exists)
347
+ continue;
348
+ let html;
349
+ try {
350
+ html = await BaseFileManager.readFileAsString(filePath);
351
+ }
352
+ catch {
353
+ const buf = await BaseFileManager.readFileAsBuffer(filePath);
354
+ if (typeof Buffer !== 'undefined' && Buffer.isBuffer(buf)) {
355
+ html = buf.toString('utf-8');
356
+ }
357
+ else if (typeof Blob !== 'undefined' && buf instanceof Blob) {
358
+ html = await buf.text();
359
+ }
360
+ else if (buf instanceof ArrayBuffer) {
361
+ html = new TextDecoder('utf-8', { fatal: false }).decode(buf);
362
+ }
363
+ else {
364
+ const v = buf;
365
+ html = new TextDecoder('utf-8', { fatal: false }).decode(new Uint8Array(v.buffer, v.byteOffset, v.byteLength));
366
+ }
367
+ }
368
+ // seed:property/ placeholders are filled in after phase 1 whatever the data URI policy. A
369
+ // placeholder naming no usable property fails here, before anything is uploaded.
370
+ const refs = findSeedPropertyRefsInHtml(html);
371
+ for (const name of refs)
372
+ resolveSeedPropertyRefTarget(item, name);
373
+ if (refs.length > 0)
374
+ deferred.add(htmlSeedLocalId.trim());
375
+ const policy = resolveEffectiveHtmlEmbeddedDataUriPolicy(def, publishPolicy);
376
+ if (policy !== 'materialize')
377
+ continue;
378
+ const extracted = await extractDataUriImagesFromHtml(html);
379
+ if (extracted.length === 0)
380
+ continue;
381
+ deferred.add(htmlSeedLocalId.trim());
382
+ for (const ent of extracted) {
383
+ const { seedLocalId: imageSeedLocalId } = await createImageItemFromBytes(ent.bytes, ent.mimeType);
384
+ const now = Date.now();
385
+ await appDb.insert(htmlEmbeddedImageCoPublish).values({
386
+ parentSeedLocalId: item.seedLocalId,
387
+ htmlSeedLocalId: htmlSeedLocalId.trim(),
388
+ imageSeedLocalId,
389
+ stableKey: ent.stableKey,
390
+ createdAt: now,
391
+ }).onConflictDoNothing();
392
+ }
393
+ }
394
+ }
395
+ function normalizeDataTypeLocal(dt) {
396
+ if (!dt)
397
+ return '';
398
+ return dt.charAt(0).toUpperCase() + dt.slice(1).toLowerCase();
399
+ }
400
+ /**
401
+ * After phase-1 uploads, rewrite Html files on disk: data URI → Arweave gateway URL, and
402
+ * `seed:property/<name>` → the gateway URL of that property's upload.
403
+ *
404
+ * `deferredHtmlSeedLocalIds` (from {@link prepareHtmlEmbeddedImagesForPublish}) limits the rewrite to
405
+ * the Html held back from phase 1; without it, every Html of the item and its co-published drafts is
406
+ * considered.
407
+ */
408
+ async function rewriteHtmlEmbeddedImagesOnDisk(parentSeedLocalId, uploadedTransactions, deferredHtmlSeedLocalIds) {
409
+ const appDb = BaseDb.getAppDb();
410
+ if (!appDb)
411
+ return;
412
+ const parentItem = await Item.find({ seedLocalId: parentSeedLocalId });
413
+ if (!parentItem)
414
+ return;
415
+ const txBySeedLocalId = new Map();
416
+ for (const u of uploadedTransactions) {
417
+ if (u.seedLocalId && u.txId) {
418
+ txBySeedLocalId.set(u.seedLocalId.trim(), u.txId.trim());
419
+ }
420
+ }
421
+ const deferred = deferredHtmlSeedLocalIds
422
+ ? new Set(deferredHtmlSeedLocalIds.map((id) => id.trim()))
423
+ : undefined;
424
+ // The parent's Html and that of the draft items published with it (see prepareHtmlEmbeddedImagesForPublish).
425
+ for (const item of [parentItem, ...(await getRelatedDraftsCoPublishedWith(parentItem))]) {
426
+ await rewriteHtmlEmbeddedImagesOfItem(appDb, item, txBySeedLocalId, deferred);
427
+ }
428
+ }
429
+ async function rewriteHtmlEmbeddedImagesOfItem(appDb, parentItem, txBySeedLocalId, deferred) {
430
+ const rows = await appDb
431
+ .select()
432
+ .from(htmlEmbeddedImageCoPublish)
433
+ .where(eq(htmlEmbeddedImageCoPublish.parentSeedLocalId, parentItem.seedLocalId));
434
+ for (const p of parentItem.properties) {
435
+ const def = p.propertyDef;
436
+ if (!def || normalizeDataTypeLocal(def.dataType) !== ModelPropertyDataTypes.Html)
437
+ continue;
438
+ const snap = p.getService().getSnapshot();
439
+ const ctx = 'context' in snap ? snap.context : null;
440
+ const htmlSeedLocalId = typeof ctx?.propertyValue === 'string' ? ctx.propertyValue.trim() : '';
441
+ const refResolved = ctx?.refResolvedValue;
442
+ if (!htmlSeedLocalId || !refResolved)
443
+ continue;
444
+ if (deferred && !deferred.has(htmlSeedLocalId))
445
+ continue;
446
+ const htmlRows = rows.filter((r) => String(r.htmlSeedLocalId).trim() === htmlSeedLocalId);
447
+ const filePath = `${BaseFileManager.getFilesPath('html')}/${refResolved}`;
448
+ if (!(await BaseFileManager.pathExists(filePath)))
449
+ continue;
450
+ const html = await BaseFileManager.readFileAsString(filePath);
451
+ const replacements = new Map();
452
+ for (const r of htmlRows) {
453
+ const txId = txBySeedLocalId.get(r.imageSeedLocalId.trim());
454
+ if (!txId)
455
+ continue;
456
+ const dataUri = await findDataUriForStableKey(html, r.stableKey);
457
+ if (dataUri)
458
+ replacements.set(dataUri, getArweaveUrlForTransaction(txId));
459
+ }
460
+ const urlByPropertyName = new Map();
461
+ for (const name of findSeedPropertyRefsInHtml(html)) {
462
+ const txId = await resolveSeedPropertyRefTxId(parentItem, name, txBySeedLocalId);
463
+ urlByPropertyName.set(name, getArweaveUrlForTransaction(txId));
464
+ }
465
+ const newHtml = replaceSeedPropertyRefsInHtml(replaceDataUrisInParsedHtml(html, replacements), urlByPropertyName);
466
+ if (newHtml === html)
467
+ continue;
468
+ try {
469
+ await BaseFileManager.saveFile(filePath, newHtml);
470
+ }
471
+ catch {
472
+ const fs = await BaseFileManager.getFs();
473
+ fs.writeFileSync(filePath, newHtml);
474
+ }
475
+ p.getService().send({
476
+ type: 'updateContext',
477
+ renderValue: newHtml,
478
+ });
479
+ }
480
+ }
481
+ async function findDataUriForStableKey(html, stableKey) {
482
+ const entries = await extractDataUriImagesFromHtml(html);
483
+ const hit = entries.find((e) => e.stableKey === stableKey);
484
+ return hit?.dataUri;
485
+ }
486
+ /**
487
+ * Remove co-publish rows after a successful publish for this parent seed.
488
+ */
489
+ async function clearHtmlEmbeddedImageCoPublishRows(parentSeedLocalId) {
490
+ const appDb = BaseDb.getAppDb();
491
+ if (!appDb || !parentSeedLocalId)
492
+ return;
493
+ await appDb
494
+ .delete(htmlEmbeddedImageCoPublish)
495
+ .where(eq(htmlEmbeddedImageCoPublish.parentSeedLocalId, parentSeedLocalId.trim()));
496
+ }
26
497
 
27
498
  /**
28
499
  * `Promise.all(items.map(fn))` with at most `limit` calls in flight. Results keep the input order.
@@ -134,21 +605,6 @@ const buildPublishUploadData = (data, contentType, target, options) => {
134
605
  ...target,
135
606
  };
136
607
  };
137
- const DATA_URI_IMAGE = /^data:(image\/[a-zA-Z0-9.+-]+);base64,([\s\S]*)$/i;
138
- function decodeDataUriImage(dataUri) {
139
- const m = DATA_URI_IMAGE.exec((dataUri ?? '').trim());
140
- if (!m)
141
- return null;
142
- try {
143
- const mimeType = m[1].toLowerCase().trim();
144
- const base64 = m[2].replace(/\s/g, '');
145
- const binary = Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
146
- return { mimeType, bytes: binary };
147
- }
148
- catch {
149
- return null;
150
- }
151
- }
152
608
  const getStorageSeedUploadData = async (itemStorageSeedProperties, options) => {
153
609
  const uploads = [];
154
610
  for (const itemProperty of itemStorageSeedProperties) {
@@ -215,15 +671,11 @@ async function appendCoPublishedImageUploadData(item, uploads, options) {
215
671
  continue;
216
672
  const st = imageItem.internalProperties['storageTransactionId'] ??
217
673
  imageItem.allProperties['storageTransactionId'];
218
- const stSnap = st?.getService().getSnapshot();
219
- const stCtx = stSnap && 'context' in stSnap ? stSnap.context : undefined;
220
- const stValue = typeof stCtx?.propertyValue === 'string'
221
- ? (stCtx.propertyValue ?? '')
222
- : '';
223
- const decoded = decodeDataUriImage(stValue);
674
+ const filePath = await findEmbeddedImageFilePath(imageItem.seedLocalId);
224
675
  const more = [];
225
- if (decoded && st && st.localId && st.versionLocalId) {
226
- more.push(buildPublishUploadData(decoded.bytes, decoded.mimeType, {
676
+ if (filePath && st && st.localId && st.versionLocalId) {
677
+ const { bytes, contentType } = await readUploadFile(filePath);
678
+ more.push(buildPublishUploadData(bytes, contentType, {
227
679
  itemPropertyName: st.propertyName,
228
680
  itemPropertyLocalId: st.localId,
229
681
  seedLocalId: imageItem.seedLocalId,
@@ -643,5 +1095,14 @@ const getPublishUploads = async (item, uploads = [], relatedItemProperty, option
643
1095
  return uploads;
644
1096
  };
645
1097
 
646
- export { CREATE_TRANSACTION_CONCURRENCY, getPublishUploadData, getPublishUploads, itemHasPublishUploadCandidates, resolveItemStorageChildFile };
647
- //# sourceMappingURL=getPublishUploads-J-143iSV.js.map
1098
+ var getPublishUploads$1 = /*#__PURE__*/Object.freeze({
1099
+ __proto__: null,
1100
+ CREATE_TRANSACTION_CONCURRENCY: CREATE_TRANSACTION_CONCURRENCY,
1101
+ getPublishUploadData: getPublishUploadData,
1102
+ getPublishUploads: getPublishUploads,
1103
+ itemHasPublishUploadCandidates: itemHasPublishUploadCandidates,
1104
+ resolveItemStorageChildFile: resolveItemStorageChildFile
1105
+ });
1106
+
1107
+ export { HTML_EMBEDDED_MAX_IMAGES_PER_DOC as H, SEED_PROPERTY_REF_PREFIX as S, HTML_EMBEDDED_MAX_IMAGE_BYTES as a, HTML_EMBEDDED_MAX_TOTAL_BYTES as b, HtmlEmbeddedDataUriLimitError as c, HtmlSeedPropertyRefError as d, clearHtmlEmbeddedImageCoPublishRows as e, findEmbeddedImageFilePath as f, getRelatedDraftsCoPublishedWith as g, extractDataUriImagesFromHtml as h, findSeedPropertyRefsInHtml as i, getPublishUploadData as j, itemHasPublishUploadCandidates as k, replaceSeedPropertyRefsInHtml as l, resolveEffectiveHtmlEmbeddedDataUriPolicy as m, rewriteHtmlEmbeddedImagesOnDisk as n, getPublishUploads$1 as o, prepareHtmlEmbeddedImagesForPublish as p, replaceDataUrisInParsedHtml as r };
1108
+ //# sourceMappingURL=getPublishUploads-pEOrXJbF.js.map