@strifeapp/strife 1.0.0 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/content-index.d.ts +13 -0
- package/dist/content-index.js +3 -0
- package/dist/{index-Cng38i9R.js → index-BIjDe1U1.js} +2 -2
- package/dist/{index-Cng38i9R.js.map → index-BIjDe1U1.js.map} +1 -1
- package/dist/{index-DohBRVYp.js → index-Crin6Dn6.js} +2 -2
- package/dist/{index-DohBRVYp.js.map → index-Crin6Dn6.js.map} +1 -1
- package/dist/index.js +1 -1
- package/dist/secrets.d.ts +54 -0
- package/dist/secrets.js +105 -0
- package/package.json +47 -5
- package/schema.d.ts +1 -0
- package/schema.js +5 -0
- package/types.d.ts +4 -0
- package/types.js +4 -0
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Raw source of the versioned RavenDB localized content index (Jint ES5), as text.
|
|
3
|
+
*
|
|
4
|
+
* This is the versioned read-contract realization that a site deploys to its OWN
|
|
5
|
+
* database. Consumers embed this string — the Astro adapter as a RavenDB index
|
|
6
|
+
* `additionalSources` entry, the CLI `push` flow as the payload it sends to the
|
|
7
|
+
* backend conduit. It is NOT an importable/executable module: the functions inside
|
|
8
|
+
* (`map`, `load`, …) only exist in RavenDB's indexing context.
|
|
9
|
+
*
|
|
10
|
+
* The pinned `@strifeapp/strife` version is what pins this index version, so two
|
|
11
|
+
* sites on different versions deploy different index sources to different DBs.
|
|
12
|
+
*/
|
|
13
|
+
export declare const source: string;
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// AUTO-GENERATED by scripts/gen-content-index.mjs from data/ravendb/localized-content-index.js.
|
|
2
|
+
// Do not edit by hand — re-run `npm run build`.
|
|
3
|
+
export const source = "/**\n * -----------------------------------------------------------------------------\n * STRIFE CONTENT INDEX — L10N + StrifeUri + Template-Aware Relations\n * -----------------------------------------------------------------------------\n * What this does\n * Projects Strife CMS documents into a query‑friendly, localized, relation‑expanded\n * shape with one entry per locale. It keeps a deterministic output and a\n * centralized storage policy (Corax‑safe).\n * Cycle safety and performance caching.\n *\n * Canonical root fields (unchanged semantics)\n * - id, locale, displayName, url, origin, collection\n * - publishedAt, createdAt, changedAt, dependencies, labels, deleted\n *\n * Root template (whitelist + localizable)\n * - Root fields are populated from the document's template. Scalars marked\n * localizable are translated using the current entry's locale and stored.\n * - Non‑localizable scalars are index‑only at root.\n * - Arrays/objects (relations, chapters, content objects) are stored.\n * - Reserved root names can never be redefined by editors.\n *\n * Relations (template‑driven for referenced docs)\n * - Relations are detected by value shape (array of GUIDs or { id: GUID }).\n * - For each referenced GUID, the target document is loaded and projected with\n * its template (resolved by collection), using the ROOT entry's locale for\n * any localizable scalars.\n * - Order is preserved. Only GUIDs are followed. Cycles are prevented via a\n * visit cache.\n *\n * Nested content by shape (no template loads)\n * - Chapters: arrays of small objects; expanded recursively by shape.\n * - Content‑template (object): expanded recursively by shape.\n * - While expanding by shape, if a field is a relation array by shape, those\n * relations are projected via templates (same as above). Otherwise, values\n * are copied through. No per‑field localization occurs in shape expansion.\n *\n * StrifeUri\n * - Form: strife://<docId>.<collection>.<db>/<path>\n * - Resolution: loads the target doc and walks the path; the first path\n * segment is localized with the ROOT entry's locale. The resolved value can be:\n * • a scalar → copied as is\n * • an object/array → expanded by shape\n * • a relation array → projected via templates\n *\n * Storage policy (centralized at root copy step)\n * - Arrays/objects → storeAs\n * - Scalars localizable at root → storeAs (so projections return translated strings)\n * - Scalars not localizable → indexAs (leaner index)\n * - Root url is always stored\n * - Keep per‑field storage/analyzer consistent across documents (Corax‑safe)\n *\n * Caching & cycle safety\n * - docCache: documents, tplCache: templates, labelCache: labels\n * - visit cache prevents cycles and provides memoization per entry\n * - URL builder protects against origin cycles via a local visited set\n *\n * Localization model\n * - Emits one entry per configured locale.\n * - Root scalars marked localizable are translated and stored.\n * - Referenced docs projected via templates also translate localizable scalars\n * using the ROOT locale. displayName is treated as non‑localized.\n * - Shape expansion itself does not localize values, except StrifeUri's first\n * path segment at dereference time.\n *\n * Collection mapping\n * - This index must map BOTH 'Contents' AND 'Drafts' collections.\n * - Draft entries are emitted with draft: true so consumers can filter.\n * - When building URLs for draft entries, the origin chain falls back to\n * parent draft documents when the published parent lacks the locale slug.\n *\n * Determinism & engine constraints\n * - ES5‑only (no for..of, no arrow functions).\n * - Deterministic shapes under the same inputs.\n * - Relation depth is capped at MAX_RELATION_DEPTH hops; cycles are still safe.\n * -----------------------------------------------------------------------------\n */\n\n\nvar MAX_RELATION_DEPTH = 1;\n\nvar RESERVED_ROOT_FIELDS = {\n url: true,\n collection: true,\n publishedAt: true,\n createdAt: true,\n changedAt: true,\n labels: true,\n locale: true,\n origin: true,\n id: true,\n docId: true,\n displayName: true,\n dependencies: true,\n deleted: true,\n draft: true\n};\n\nfunction storeAs(name, value) {\n return { $value: value, $name: name, $options: { storage: true } };\n}\n\nfunction indexAs(name, value) {\n return { $value: value, $name: name, $options: { storage: false } };\n}\n\nfunction loadDocCached(id, docCache) {\n if (!id) return null;\n var key = id;\n if (docCache.has(key)) return docCache.get(key);\n var d = load(id, '@all_docs');\n if (d) docCache.set(key, d);\n return d;\n}\n\nfunction loadTemplateByCollectionCached(templateId, tplCache) {\n if (!templateId) return null;\n if (tplCache.has(templateId)) return tplCache.get(templateId);\n var t = load(templateId, 'templates');\n if (t) tplCache.set(templateId, t);\n return t;\n}\n\nfunction loadTemplateByIdCached(templateId, tplCache) {\n if (!templateId) return null;\n var key = templateId;\n if (tplCache.has(key)) return tplCache.get(key);\n var t = load(templateId, 'templates');\n if (t) tplCache.set(key, t);\n return t;\n}\n\nfunction loadLocalizationSettings() {\n return load('configurations/localization', 'configurations');\n}\n\nfunction loadLabelCached(id, labelCache) {\n if (!id) return null;\n if (labelCache.has(id)) return labelCache.get(id);\n var d = load(id, 'Labels');\n if (d) labelCache.set(id, d);\n return d;\n}\n\nfunction resolveSlug(slug, locale) {\n if (typeof slug === 'string') return slug; // legacy string format\n if (slug && locale && slug[locale]) return slug[locale]; // locale-keyed object\n return null;\n}\n\n// Checks if obj is a locale-keyed object where ALL keys are configured locales.\n// Uses configured locales (not BCP 47 syntax) to avoid false positives on\n// objects like { \"id\": \"abc\", \"no\": false } where keys happen to be 2-letter strings.\nfunction isLocaleObject(obj, configuredLocales) {\n if (!obj || typeof obj !== 'object' || Array.isArray(obj)) return false;\n var keys = Object.keys(obj);\n if (keys.length === 0) return false;\n for (var i = 0; i < keys.length; i++) {\n if (configuredLocales.indexOf(keys[i]) === -1) return false;\n }\n return true;\n}\n\nfunction buildUrlCached(doc, locale, docCache, isDraft) {\n var visited = {};\n var slugs = [];\n var c = doc;\n do {\n var nodeSlug = resolveSlug(c.slug, locale);\n // Draft URL building: if a published ancestor lacks the locale slug, try its draft\n if (!nodeSlug && isDraft) {\n var nodeCollection = c['@metadata'] ? c['@metadata']['@collection'] : null;\n if (nodeCollection !== 'Drafts') {\n var nodeId = c['@metadata'] ? c['@metadata']['@id'] : null;\n if (nodeId) {\n var draftNode = loadDocCached(nodeId + '/draft', docCache);\n if (draftNode) nodeSlug = resolveSlug(draftNode.slug, locale);\n }\n }\n }\n if (nodeSlug) slugs.unshift(nodeSlug);\n if (!c.origin || visited[c.origin.id]) break;\n visited[c.origin.id] = true;\n c = loadDocCached(c.origin.id, docCache);\n } while (c);\n\n // ENG-62: do NOT return slugs.shift() + slugs.join('/').\n // For an empty array that expression evaluates to the literal string \"undefined\"\n // (because [].shift() is undefined and undefined + '' coerces to \"undefined\").\n // For a two-element array it drops the separator (['a','b'] -> \"ab\" instead of \"a/b\").\n // Both behaviors are confirmed in api-test/Integration/Eng62LinkResolutionDiagnosticTests.\n //\n // We also can't just slugs.join('/'): the root home's slug is \"/\" by convention,\n // so ['/', 'page'] would produce \"//page\". Instead, normalize each slug (strip its\n // own leading/trailing slashes so \"/\" becomes \"\" and drops out) and prepend a\n // single leading \"/\" so URLs always start with \"/\".\n if (slugs.length === 0) return null;\n var parts = [];\n for (var si = 0; si < slugs.length; si++) {\n var s = slugs[si];\n if (typeof s !== 'string') continue;\n // Strip leading and trailing slashes from this segment. Reduces \"/\" to \"\"\n // (skipped) and leaves \"foo\" untouched.\n var stripped = s;\n while (stripped.length > 0 && stripped.charAt(0) === '/') stripped = stripped.substring(1);\n while (stripped.length > 0 && stripped.charAt(stripped.length - 1) === '/') stripped = stripped.substring(0, stripped.length - 1);\n if (stripped.length > 0) parts.push(stripped);\n }\n return '/' + parts.join('/');\n}\n\nfunction isLinkValue(val) {\n return val && typeof val === 'object' && !Array.isArray(val) &&\n typeof val.href === 'string' && typeof val.target === 'string' &&\n isGuid(val.id);\n}\n\nfunction resolveLinkHref(val, locale, docCache) {\n var doc = loadDocCached(val.id, docCache);\n if (!doc) return val.href;\n // ENG-62: do NOT use `'slug' in doc` here. RavenDB's Jint wraps loaded docs in a\n // BlittableObjectInstance whose [[HasProperty]] returns true for ANY property name,\n // making `'slug' in doc` always-true dead code. Use the @metadata collection check\n // (proven reliable) and a value-presence check instead.\n // See api-test/Integration/Eng62LinkResolutionDiagnosticTests for proof.\n var collection = doc['@metadata'] && doc['@metadata']['@collection'];\n if (collection === 'Files' || collection === 'Folders') return val.href;\n if (doc.slug == null) return val.href;\n var url = buildUrlCached(doc, locale, docCache);\n if (!url || url === 'undefined') return val.href;\n return url;\n}\n\nfunction resolveLink(val, locale, docCache) {\n return {\n id: val.id,\n text: val.text,\n href: resolveLinkHref(val, locale, docCache),\n target: val.target\n };\n}\n\nfunction resolveHtmlLinks(html, locale, docCache) {\n if (html.indexOf('data-id=\"') === -1) return html;\n\n var guidPat = '[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}';\n\n // data-id before href\n var p1 = new RegExp(\n '<a\\\\s([^>]*?)data-id=\"(' + guidPat + ')\"([^>]*?)href=\"([^\"]*)\"([^>]*?)>',\n 'g'\n );\n // ENG-62: same Jint quirk as resolveLinkHref — `'slug' in doc` is dead code on\n // a wrapped loaded doc. Use collection check + value check instead.\n var result = html.replace(p1, function(match, before, id, mid, href, after) {\n var doc = loadDocCached(id, docCache);\n if (!doc) return match;\n var coll = doc['@metadata'] && doc['@metadata']['@collection'];\n if (coll === 'Files' || coll === 'Folders') return match;\n if (doc.slug == null) return match;\n var url = buildUrlCached(doc, locale, docCache);\n if (!url || url === 'undefined') return match;\n return '<a ' + before + 'data-id=\"' + id + '\"' + mid + 'href=\"' + url + '\"' + after + '>';\n });\n\n // href before data-id\n var p2 = new RegExp(\n '<a\\\\s([^>]*?)href=\"([^\"]*)\"([^>]*?)data-id=\"(' + guidPat + ')\"([^>]*?)>',\n 'g'\n );\n result = result.replace(p2, function(match, before, href, mid, id, after) {\n var doc = loadDocCached(id, docCache);\n if (!doc) return match;\n var coll = doc['@metadata'] && doc['@metadata']['@collection'];\n if (coll === 'Files' || coll === 'Folders') return match;\n if (doc.slug == null) return match;\n var url = buildUrlCached(doc, locale, docCache);\n if (!url || url === 'undefined') return match;\n return '<a ' + before + 'href=\"' + url + '\"' + mid + 'data-id=\"' + id + '\"' + after + '>';\n });\n\n return result;\n}\n\nfunction getTranslator(locale, defaultLocale, fallbackToPrimary) {\n return function (obj) {\n if (!obj) return null;\n if (typeof obj === 'object' && obj.hasOwnProperty) {\n if (obj.hasOwnProperty(locale)) return obj[locale];\n // if (fallbackToPrimary && locale && locale.length > 2) {\n // var base = locale.slice(0, 2);\n // if (obj.hasOwnProperty(base)) return obj[base];\n // }\n //return obj[defaultLocale];\n }\n // Return non-objects as-is only for the default locale (handles false→true\n // mismatch where editor.localizable is true but stored value is still a\n // plain scalar). Non-default locales get null — the value was never translated.\n if ((typeof obj === 'string' || typeof obj === 'number') && locale === defaultLocale) return obj;\n return null;\n };\n}\n\nfunction isLocalized(obj, configuredLocales) {\n if (!obj || typeof obj !== 'object' || Array.isArray(obj)) return false;\n if (!obj.hasOwnProperty) return false;\n for (var i = 0; i < configuredLocales.length; i++) {\n if (obj.hasOwnProperty(configuredLocales[i])) return true;\n }\n return false;\n}\n\nfunction isGuid(s) {\n return typeof s === 'string' &&\n /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(s);\n}\nfunction isRefLike(x) {\n // GUID string id, or object with GUID `id`\n if (typeof x === 'string') return isGuid(x);\n if (!x || typeof x !== 'object') return false;\n return typeof x.id === 'string' && isGuid(x.id) && Object.keys(x).length <= 2;\n}\nfunction isRelationArray(v) {\n if (!v || !Array.isArray(v)) return false;\n if (v.length === 0) return false; // empty arrays are ambiguous\n for (var i = 0; i < v.length; i++) {\n if (!isRefLike(v[i])) return false;\n }\n return true;\n}\n\nvar strifeUriPattern = /^strife:\\/\\/(?<id>[-\\w_]*)\\.(?<coll>[\\w_-]*)\\.(?<db>[\\w_-]*)(?<path>[-\\w_./]*)?$/;\nfunction isStrifeUri(value) {\n var match = strifeUriPattern.exec(value || '');\n if (!match) return null;\n try {\n var path = match.groups.path || '';\n var segs = path.length > 1 ? path.slice(1).split('/') : [];\n return {\n original: value,\n db: match.groups.db,\n collection: match.groups.coll,\n docId: match.groups.id, // may be non-GUID by design for StrifeUri\n segments: segs\n };\n } catch (e) {\n return null;\n }\n}\n\nfunction tryGetReferencedValue(strifeUri, populationContext, docCache) {\n var document = loadDocCached(strifeUri.docId, docCache);\n if (!document) return null;\n\n var val = document;\n if (strifeUri.segments.length > 0) {\n // first segment may be localized; use isLocalized to distinguish locale-keyed objects\n var first = strifeUri.segments[0];\n var rawFirst = val[first];\n if (populationContext.isLocalized(rawFirst)) {\n val = populationContext.translate(rawFirst);\n } else {\n val = rawFirst;\n }\n for (var i = 1; i < strifeUri.segments.length; i++) {\n if (val == null) break;\n var segment = strifeUri.segments[i];\n val = val[segment];\n }\n }\n return val;\n}\n\nfunction resolveStrifeUriIfAny(value, populationContext, docCache) {\n var maybeUri = isStrifeUri(value);\n return maybeUri ? tryGetReferencedValue(maybeUri, populationContext, docCache) : value;\n}\n\nfunction loadRelatedLabels(labelIdsArray, labelCache) {\n if (!labelIdsArray || !labelIdsArray.length) return null;\n var out = [];\n for (var i = 0; i < labelIdsArray.length; i++) {\n var lid = labelIdsArray[i];\n var d = loadLabelCached(lid, labelCache);\n if (d) out.push(d);\n }\n return out;\n}\n\nfunction getVisitEntry(visit, id) {\n var e = visit.get(id);\n if (!e) { e = { state: 'done', node: null }; visit.set(id, e); }\n return e;\n}\n\nfunction isVisiting(visit, id) {\n var e = visit.get(id);\n return e ? e.state === 'visiting' : false;\n}\n\nfunction markVisiting(visit, id) {\n var e = getVisitEntry(visit, id);\n e.state = 'visiting';\n}\n\nfunction markDone(visit, id) {\n var e = getVisitEntry(visit, id);\n e.state = 'done';\n}\n\nfunction getCachedNode(visit, id) {\n var e = visit.get(id);\n return e && e.node ? e.node : null;\n}\n\nfunction setCachedNode(visit, id, node) {\n var e = getVisitEntry(visit, id);\n e.node = node;\n}\n\nfunction isContentTemplateNode(v) {\n return v && typeof v === 'object' && !Array.isArray(v) &&\n v['@strife'] && v['@strife'].template;\n}\n\nfunction isChaptersArray(v) {\n if (!v || !Array.isArray(v)) return false;\n if (v.length === 0) return false;\n for (var i = 0; i < v.length; i++) {\n var it = v[i];\n if (!it || !it['@strife'] || !it['@strife'].template) return false;\n }\n return true;\n}\n\nfunction populateByShape(document, out, populationContext, visit,\n docCache, tplCache, labelCache, hopsLeft) {\n if (!document || typeof document !== 'object') return;\n\n for (var prop in document) {\n if (!document || !document.hasOwnProperty || !document.hasOwnProperty(prop)) continue;\n\n // Keep metadata decorations as-is\n if (prop.charAt(0) === '@') { out[prop] = document[prop]; continue; }\n\n var val = document[prop];\n // StrifeUri resolution\n val = resolveStrifeUriIfAny(val, populationContext, docCache);\n\n // Chapters\n if (isChaptersArray(val)) {\n var arr = [];\n for (var ci = 0; ci < val.length; ci++) {\n var chapter = val[ci];\n if (chapter && chapter['@strife'] && chapter['@strife'].template) {\n var child = {};\n populateByShape(chapter, child, populationContext, visit,\n docCache, tplCache, labelCache, hopsLeft);\n arr.push(child);\n }\n }\n out[prop] = arr;\n continue;\n }\n\n // Content-template node\n if (isContentTemplateNode(val)) {\n var nested = {};\n populateByShape(val, nested, populationContext, visit,\n docCache, tplCache, labelCache, hopsLeft);\n out[prop] = nested;\n continue;\n }\n\n // Relations (GUID-strict)\n if (isRelationArray(val)) {\n var related = projectRelationsIfAny(val, populationContext, visit, docCache, tplCache, labelCache, hopsLeft);\n if (related) { out[prop] = related; continue; }\n }\n\n // Link resolution\n if (isLinkValue(val)) {\n out[prop] = resolveLink(val, populationContext.locale, docCache);\n continue;\n }\n if (Array.isArray(val) && val.length > 0 && isLinkValue(val[0])) {\n var linkArr = [];\n for (var lki = 0; lki < val.length; lki++) {\n linkArr.push(isLinkValue(val[lki]) ? resolveLink(val[lki], populationContext.locale, docCache) : val[lki]);\n }\n out[prop] = linkArr;\n continue;\n }\n\n // HTML link resolution (rich text fields)\n if (typeof val === 'string' && val.indexOf('data-id=\"') !== -1) {\n out[prop] = resolveHtmlLinks(val, populationContext.locale, docCache);\n continue;\n }\n\n // Default: copy-through (no localization inside nested)\n out[prop] = val;\n }\n\n if (document['@strife'] && !out['@strife']) out['@strife'] = document['@strife'];\n}\n\nfunction projectRelationsIfAny(value, populationContext, visit, docCache, tplCache, labelCache, hopsLeft) {\n if (!isRelationArray(value)) return null;\n if (hopsLeft <= 0) return [];\n var refs = [];\n for (var i = 0; i < value.length; i++) {\n var v = value[i];\n var idStr = (typeof v === 'string') ? v : (v && v.id);\n if (isGuid(idStr)) refs.push(idStr);\n }\n return loadRelatedDocumentsRecurse(refs, populationContext, visit, docCache, tplCache, labelCache, hopsLeft);\n}\n\nfunction populateValuesByEditor(document, template, result, populationContext, visit,\n docCache, tplCache, labelCache, isRootLevel, hopsLeft) {\n if (!template || !template.editors) return;\n var tEditors = template.editors || [];\n var i, editor;\n\n function processEditor(editor, isRoot) {\n if (!editor || !editor.editor || !editor.editor.propertyName) return;\n\n var propertyName = editor.editor.propertyName;\n\n // Never let editors redefine reserved fields (consistent everywhere)\n if (RESERVED_ROOT_FIELDS[propertyName]) return;\n\n // Read value with optional localization\n var rawVal = document[propertyName];\n\n // true→false mismatch: editor is no longer localizable but value is still a locale-object\n if (!editor.localizable && isLocaleObject(rawVal, populationContext.locales)) {\n var defVal = rawVal[populationContext.defaultLocale];\n rawVal = (defVal != null) ? defVal : rawVal[Object.keys(rawVal)[0]];\n if (rawVal == null) rawVal = null;\n }\n\n var docValue = (editor.localizable) ? populationContext.translate(rawVal) : rawVal;\n\n // StrifeUri resolution\n docValue = resolveStrifeUriIfAny(docValue, populationContext, docCache);\n\n // Relations (GUID-strict) — detect by value shape\n var relatedDocs = projectRelationsIfAny(docValue, populationContext, visit, docCache, tplCache, labelCache, hopsLeft);\n if (relatedDocs) { result[propertyName] = relatedDocs; return; }\n\n // Chapters (nested without template loads)\n if (editor.editor.type === 'chapters') {\n if (docValue == null) { // missing translation\n result[propertyName] = null; // keep null instead of dropping field\n return;\n }\n if (!Array.isArray(docValue)) return;\n var docResults = [];\n for (var ci = 0; ci < docValue.length; ci++) {\n var chapter = docValue[ci];\n if (chapter && chapter['@strife'] && chapter['@strife'].template) {\n var child = {};\n populateByShape(chapter, child, populationContext, visit,\n docCache, tplCache, labelCache, hopsLeft);\n docResults.push(child);\n }\n }\n result[propertyName] = docResults;\n return;\n }\n\n // Content-template (nested without template loads)\n if (editor.editor.type === 'content-template') {\n if (docValue == null) { // missing translation\n result[propertyName] = null;\n return;\n }\n if (docValue && typeof docValue === 'object') {\n var nested = {};\n populateByShape(docValue, nested, populationContext, visit,\n docCache, tplCache, labelCache, hopsLeft);\n result[propertyName] = nested;\n }\n return;\n }\n\n // Link resolution\n if (isLinkValue(docValue)) {\n result[propertyName] = resolveLink(docValue, populationContext.locale, docCache);\n return;\n }\n if (Array.isArray(docValue) && docValue.length > 0 && isLinkValue(docValue[0])) {\n var linkResults = [];\n for (var lki = 0; lki < docValue.length; lki++) {\n linkResults.push(isLinkValue(docValue[lki]) ? resolveLink(docValue[lki], populationContext.locale, docCache) : docValue[lki]);\n }\n result[propertyName] = linkResults;\n return;\n }\n\n // HTML link resolution (rich text fields)\n if (typeof docValue === 'string' && docValue.indexOf('data-id=\"') !== -1) {\n result[propertyName] = resolveHtmlLinks(docValue, populationContext.locale, docCache);\n return;\n }\n\n // Other fields: plain values (localized at root when editor.localizable)\n if (docValue !== undefined) {\n result[propertyName] = docValue;\n }\n }\n\n for (i = 0; i < tEditors.length; i++) {\n processEditor(tEditors[i], isRootLevel);\n }\n\n if (document['@strife']) result['@strife'] = document['@strife'];\n}\n\nfunction projectDocumentWithTemplate(doc, populationContext, visit,\n docCache, tplCache, labelCache, locale, hopsLeft) {\n var collection = doc && doc['@metadata'] ? doc['@metadata']['@collection'] : null;\n var templateId = 'templates/' + (collection === 'Drafts' ? doc['@metadata']['@base-collection'] : collection);\n var tpl = loadTemplateByCollectionCached(templateId, tplCache);\n var labelsArr = Array.isArray(doc.labels) ? doc.labels : null;\n\n var result = {\n id: doc['@metadata']['@id'],\n url: buildUrlCached(doc, locale, docCache),\n collection: collection,\n displayName: doc.displayName,\n slug: resolveSlug(doc.slug, locale),\n publishedDate: doc.publishedDate,\n labels: loadRelatedLabels(labelsArr, labelCache)\n };\n\n // Fill fields per template (use root locale via populationContext.translate)\n if (tpl && tpl.editors) {\n populateValuesByEditor(doc, tpl, result, populationContext, visit,\n docCache, tplCache, labelCache, false, hopsLeft);\n }\n\n return result;\n}\n\nfunction loadRelatedDocumentsRecurse(refGuids, populationContext, visit,\n docCache, tplCache, labelCache, hopsLeft) {\n if (!refGuids) return null;\n\n var results = [];\n for (var i = 0; i < refGuids.length; i++) {\n var id = refGuids[i];\n if (!isGuid(id)) continue;\n\n if (isVisiting(visit, id)) continue;\n\n var cached = getCachedNode(visit, id);\n if (cached) { results.push(cached); continue; }\n\n markVisiting(visit, id);\n var doc = loadDocCached(id, docCache);\n\n if (doc) {\n var projected = projectDocumentWithTemplate(doc, populationContext, visit,\n docCache, tplCache, labelCache, populationContext.locale, hopsLeft - 1);\n setCachedNode(visit, id, projected);\n results.push(projected);\n }\n\n markDone(visit, id);\n }\n\n return results;\n}\n\nfunction mapDocument(document) {\n var collection = document['@metadata']['@collection'];\n var templateId = 'templates/' + (collection === 'Drafts' ? document['@metadata']['@base-collection'] : collection);\n var template = load(templateId, 'templates');\n if (!template || !template.editors || document.deleted || document.archived) return null;\n\n var l10n = loadLocalizationSettings();\n var locales = (l10n && Array.isArray(l10n.locales)) ? l10n.locales : [l10n && l10n.defaultLocale ? l10n.defaultLocale : 'en'];\n\n var _isDraft = collection === 'Drafts';\n\n // Shared per-document caches (shared across locales)\n var _docCache = new Map();\n var _tplCache = new Map();\n var _labelCache = new Map();\n\n var entries = [];\n\n // Precompute root labels (loaded in helper)\n var rootLabelIds = Array.isArray(document.labels) ? document.labels : null;\n\n // Precompute dependencies (ES5)\n var depsArr = [];\n if (document.dependencies && Array.isArray(document.dependencies)) {\n for (var di = 0; di < document.dependencies.length; di++) {\n var dep = document.dependencies[di];\n if (dep && typeof dep.id === 'string') depsArr.push(dep.id);\n }\n }\n\n // Build a set of localizable root scalar fields from the template\n var localizableRoot = {};\n if (template && template.editors) {\n for (var li0 = 0; li0 < template.editors.length; li0++) {\n var ed0 = template.editors[li0];\n if (!ed0 || !ed0.editor || !ed0.editor.propertyName) continue;\n var t0 = ed0.editor.type;\n if (t0 !== 'related' && t0 !== 'references' && t0 !== 'content-template' && t0 !== 'chapters') {\n if (ed0.localizable === true) localizableRoot[ed0.editor.propertyName] = true;\n }\n }\n }\n\n for (var li = 0; li < locales.length; li++) {\n\n var currentLocale = locales[li];\n if (document.locales && Array.isArray(document.locales)) {\n var found = false;\n for (var k = 0; k < document.locales.length; k++) {\n if (document.locales[k] === currentLocale) { found = true; break; }\n }\n if (!found) continue;\n }\n\n var translate = getTranslator(currentLocale, l10n.defaultLocale, l10n.fallbackToPrimary);\n var checkLocalized = function (obj) { return isLocalized(obj, locales); };\n\n // Root result (stored fields)\n var result = {\n id: storeAs('id',Id(document)),\n docId: storeAs('docId', document['@metadata']['@id']),\n locale: storeAs('locale', currentLocale),\n displayName: storeAs('displayName',document.displayName),\n url: template.disableURL ? null : storeAs('url', buildUrlCached(document, currentLocale, _docCache, _isDraft)),\n origin: storeAs('origin', document.origin ? document.origin.id : null ),\n collection: storeAs('collection', collection === 'Drafts' ? document['@metadata']['@base-collection'] : collection),\n draft: storeAs('draft', (document['@metadata']['@collection'] === 'Drafts')),\n publishedAt: storeAs('publishedAt', document.publishedDate),\n createdAt: storeAs('createdAt', document.createdAt),\n changedAt: storeAs('changedAt', document.changedAt),\n dependencies: storeAs('dependencies', depsArr),\n //labels: storeAs('labels', loadRelatedLabels(rootLabelIds, _labelCache)),\n labels: storeAs('labels', loadRelatedLabels(rootLabelIds, _labelCache).map(function(label) { return label.name; })),\n deleted: indexAs('deleted', document.deleted)\n };\n\n // Visit cache per-locale (keeps shapes deterministic per entry)\n var visit = new Map();\n\n // Build dynamic fields into a temp container using ROOT TEMPLATE (respect localizable)\n var rootContainer = {};\n populateValuesByEditor(document, template, rootContainer,\n { translate: translate, isLocalized: checkLocalized, locale: currentLocale, defaultLocale: l10n.defaultLocale, locales: locales },\n visit, _docCache, _tplCache, _labelCache, true, MAX_RELATION_DEPTH);\n\n // Copy fields from temp container into result\n // - arrays/objects -> storeAs\n // - scalars -> storeAs if localizable, else indexAs\n var keys = [];\n for (var key in rootContainer) {\n if (rootContainer && rootContainer.hasOwnProperty && rootContainer.hasOwnProperty(key)) {\n keys.push(key);\n }\n }\n\n for (var ei = 0; ei < keys.length; ei++) {\n var prop = keys[ei];\n\n // never redefine canonical root fields\n if (RESERVED_ROOT_FIELDS[prop]) continue;\n\n var val = rootContainer[prop];\n var isArray = Array.isArray(val);\n var isProjectedArray = isArray && (val.length === 0 || typeof val[0] === 'object');\n var isProjectedObject = !isArray && typeof val === 'object';\n\n if (isProjectedArray || isProjectedObject) {\n result[prop] = storeAs(prop, val);\n } else {\n if (localizableRoot[prop] === true) {\n result[prop] = storeAs(prop, val); // translated scalar → store so projections return translated value\n } else {\n result[prop] = indexAs(prop, val); // non-localizable scalar → index-only\n }\n }\n }\n\n entries.push(result);\n }\n\n return entries;\n}\n";
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=1,t=2,n=4,s=8;class a extends MessageChannel{static _instanceCache;#e=crypto.randomUUID();#t=[];#n;#s=null;#a=null;#o=null;#r=null;static get instance(){return this._instanceCache||(this._instanceCache=new a),this._instanceCache}constructor(){super(),window.__strifeInstances?(window.__strifeInstances++,console.warn(`[${window.name}] ⚠️ MULTIPLE SubscribableChannel instances detected (${window.__strifeInstances})!`),console.warn(`[${window.name}] 🔄 Please do a HARD REFRESH (Cmd+Shift+R / Ctrl+Shift+R) to clear cached SDK code`)):window.__strifeInstances=1,this.#n=new BroadcastChannel('app.broadcast')}invoke(){switch(this.port1.addEventListener('message',(t=>{t.data.cmd===e&&this.onConnected(t)}),{once:!0}),this.port1.start(),this._ready=new Promise(((e,t)=>{this.readyResolve=e,this.readyReject=t})),this._ready.then((()=>{try{window.top.postMessage({cmd:t,context:{name:window.name,height:document.body.scrollHeight,path:window.location.pathname}},'*',[this.port2])}catch(e){console.error(`[${window.name}] ❌ Failed to send HSHK:`,e),this.readyReject(e)}})),document.readyState){case'loading':case'interactive':document.onreadystatechange=()=>{'complete'===document.readyState&&this.readyResolve()};break;case'complete':this.readyResolve()}}subscribe(e){if('function'!=typeof e)throw new Error('messageHandler must be a function!');if(this.#t.push(e),null===this.#s){this.#s=e=>{this.#o=e,null===this.#r&&(this.#r=requestAnimationFrame((()=>{this.#r=null;const e=this.#o;if(this.#o=null,e)for(const t of this.#t)try{t(e)}catch(e){console.error(`[${window.name}] Error in subscriber:`,e)}})))},this.#a=e=>{try{this.#n.postMessage({...e.data,_sourceInstanceId:this.#e,_sourceType:'iframe',_sourceName:window.name})}catch(e){console.error(`[${window.name}] Error in handleBroadcastMessage:`,e)}};const e=e=>{try{if(e.data._sourceInstanceId===this.#e)return;const{_sourceInstanceId:t,_sourceType:n,_sourceName:s,...a}=e.data;if(a.sync&&Array.isArray(a.sync)){const e=a.sync.filter((e=>!e.currentPath||e.currentPath===window.location.pathname));if(0===e.length)return;a.sync=e}const o={...e,data:a};for(const e of this.#t)try{e(o)}catch(e){console.error(`[${window.name}] Error in subscriber:`,e)}}catch(e){console.error(`[${window.name}] Error in handleBroadcastReceived:`,e)}};this.#n.addEventListener('message',e),this.port1.addEventListener('message',this.#s)}return()=>{const t=this.#t.indexOf(e);t>-1&&this.#t.splice(t,1)}}send(e){this.port1.postMessage(e),this.#n.postMessage({...e,_sourceInstanceId:this.#e,_sourceType:'iframe',_sourceName:window.name})}onConnected(e){return e}}const o=(e,t)=>e?.split('.').reduce(((e,t)=>e?.[t]),t),r=['|','-','–','—',':'],i={SEO:{TITLE:{MISSING:'titleMissing',LENGTH:'titleLength',SEPARATORS:'titleSeparators',SEGMENTS:'titleSegments'},META_DESCRIPTION:{MISSING:'metaDescriptionMissing',LENGTH:'metaDescriptionLength'},KEYWORDS:{COUNT:'keywordCount',DENSITY:'keywordDensity',TITLE:'keywordTitle',META_DESCRIPTION:'keywordMetaDescription',URL:'keywordUrl',HEADINGS:'keywordHeadings',FIRST_PARAGRAPH:'keyword1stParagraph',DISTINCT:'keywordDistinct'}},CONTENT:{PARAGRAPH_TOO_LONG:'contentParagraphTooLong',SENTENCE_TOO_LONG:'contentSentenceTooLong',LIX:'contentLix',FLESCH_EASE:'contentFleschEase',FLESCH_KINCAID:'contentFleschKincaid',GUNNING_FOG:'contentGunningFog',COLEMAN_LIAU:'contentColemanLiau',LONG_WORDS:'contentLongWords',COMPLEX_WORDS:'contentComplexWords',AVERAGE_WORDS_PER_SENTENCE:'contentAverageWordsPerSentence'}};function c(e){const t={};t[i.SEO.TITLE.MISSING]={value:0===e.length},t[i.SEO.TITLE.LENGTH]={value:e.length};const n=function(e){const t=r.find((t=>e.includes(t)));return t?{hasSeparator:!0,segments:e.split(t).map((e=>e.trim())),separator:t}:{hasSeparator:!1,segments:[e],separator:null}}(e);return t[i.SEO.TITLE.SEPARATORS]={value:n.hasSeparator},t[i.SEO.TITLE.SEGMENTS]={value:n.segments.length},t}function l(e){const t={};return t[i.SEO.META_DESCRIPTION.MISSING]={value:0===e.length},t[i.SEO.META_DESCRIPTION.LENGTH]={value:e.length},t}function d(e){return e.toLowerCase().replace(/[.,/#!$%^&*;:{}=\-_`~()]/g,'').replace(/\s+/g,' ').trim()}function h(e,t){const n=d(e),s=d(t),a=n.split(' '),o=s.split(' '),r=[];if(1===o.length){const t=new RegExp(`\\b${i=s,i.replace(/[.*+?^${}()|[\]\\]/g,'\\$&')}\\b`,'gi');return e.match(t)||[]}var i;for(let t=0;t<=a.length-o.length;t++){if(a.slice(t,t+o.length).join(' ')===s){const n=e.split(/\s+/).slice(t,t+o.length).join(' ');r.push(n)}}return r}function u(e,t){let n={};if(!t.trim())return n;const s=t.split(',').map((e=>e.trim())).filter((e=>e.length>0));return s.forEach(((t,s)=>{const a=function(e,t){const n=e.body.textContent||'',s=d(n).split(/\s+/).length,a=h(n,t),o=a.length,r=t.split(/\s+/).length,i=o*r/s*100,c=e.querySelector('title')?.textContent||'',l=h(c,t).length>0,u=e.querySelector('p')?.textContent||'',E=h(u,t).length>0,S=Array.from(e.querySelectorAll('h1')).reduce(((e,n)=>e+h(n.textContent||'',t).length),0),g=Array.from(e.querySelectorAll('h2')).reduce(((e,n)=>e+h(n.textContent||'',t).length),0),m=Array.from(e.querySelectorAll('h3')).reduce(((e,n)=>e+h(n.textContent||'',t).length),0),p=e.querySelector('meta[name="description"]')?.getAttribute('content')||'',f=h(p,t).length>0,O=e.location?.pathname||'',T=d(t).replace(/\s+/g,'-'),N=d(O).includes(T);return{density:i,count:o,inTitle:l,inFirstParagraph:E,inHeadings:{h1:S,h2:g,h3:m},inMetaDescription:f,inUrl:N,occurrences:a}}(e,t);!function(e,t,n){e[i.SEO.KEYWORDS.COUNT]||(e[i.SEO.KEYWORDS.COUNT]=[]);e[i.SEO.KEYWORDS.COUNT].push({value:t.count,additional:{keyword:n}}),e[i.SEO.KEYWORDS.DENSITY]||(e[i.SEO.KEYWORDS.DENSITY]=[]);e[i.SEO.KEYWORDS.DENSITY].push({value:t.density,additional:{keyword:n}}),e[i.SEO.KEYWORDS.TITLE]||(e[i.SEO.KEYWORDS.TITLE]=[]);e[i.SEO.KEYWORDS.TITLE].push({value:t.inTitle,additional:{keyword:n}}),e[i.SEO.KEYWORDS.HEADINGS]||(e[i.SEO.KEYWORDS.HEADINGS]=[]);e[i.SEO.KEYWORDS.HEADINGS].push({value:t.inHeadings.h1+t.inHeadings.h2+t.inHeadings.h3,additional:{keyword:n}}),e[i.SEO.KEYWORDS.FIRST_PARAGRAPH]||(e[i.SEO.KEYWORDS.FIRST_PARAGRAPH]=[]);e[i.SEO.KEYWORDS.FIRST_PARAGRAPH].push({value:t.inFirstParagraph,additional:{keyword:n}}),e[i.SEO.KEYWORDS.META_DESCRIPTION]||(e[i.SEO.KEYWORDS.META_DESCRIPTION]=[]);e[i.SEO.KEYWORDS.META_DESCRIPTION].push({value:t.inMetaDescription,additional:{keyword:n}}),e[i.SEO.KEYWORDS.URL]||(e[i.SEO.KEYWORDS.URL]=[]);e[i.SEO.KEYWORDS.URL].push({value:t.inUrl,additional:{keyword:n}})}(n,a,t)})),s.length>1&&function(e,t){e[i.SEO.KEYWORDS.DISTINCT]||(e[i.SEO.KEYWORDS.DISTINCT]=[]);const n=[];for(let s=0;s<t.length;s++)for(let a=s+1;a<t.length;a++){const o=E(t[s],t[a]);o>.3&&e[i.SEO.KEYWORDS.DISTINCT].push({value:0===n.length,additional:{similarities:[t[s],t[a],o]}})}}(n,s),n}function E(e,t){const n=new Set(e.toLowerCase().split(' ')),s=new Set(t.toLowerCase().split(' ')),a=new Set([...n].filter((e=>s.has(e)))),o=new Set([...n,...s]);return a.size/o.size}function S(e,t){const n=e.split(/\s+/).filter((e=>e.length>0)),s=e.split(/[.!?]+/).filter((e=>e.trim().length>0)),a=function(e){const t=e.toLowerCase().split(/\s+/);return t.reduce(((e,t)=>e+g(t)),0)}(e),o=n.filter((e=>g(e)>2)).length,r=n.length,i=s.length,c=r/i,l=a/r,d=e.replace(/\s/g,'').length/r,h=function(e){const t=e.split(/\s+/).filter((e=>e.length>0)),n=e.split(/[.!?]+/).filter((e=>e.trim().length>0)),s=t.filter((e=>e.length>6)).length;return t.length/n.length+100*s/t.length}(e);return{fleschEase:206.835-1.015*c-84.6*l,fleschKincaid:.39*c+11.8*l-15.59,gunningFog:.4*(c+o/r*100),colemanLiau:100*d*.0588-i/r*100*.296-15.8,averageWordsPerSentence:c,averageSyllablesPerWord:l,totalWords:r,totalSentences:i,complexWords:o,lix:h,longWords:n.filter((e=>e.length>15)).length}}function g(e){if((e=e.toLowerCase().replace(/[^a-z]/g,'')).length<=3)return 1;const t=(e=(e=e.replace(/(?:[^laeiouy]es|ed|[^laeiouy]e)$/,'')).replace(/^y/,'')).match(/[aeiouy]{1,2}/g);return t?t.length:1}function m(e){const t={},n=e.documentElement.lang.toLowerCase().split('-')[0]||'en',s=e.querySelectorAll('p');if(0===s.length)return;const a=[],o=[];for(const[e,t]of Array.from(s).entries()){const n=t.textContent?.trim()||'';if(0===n.length)continue;n.split(/\s+/).filter((e=>e.length>0)).length>40&&a.push(e+1);const s=n.split(/[.!?]+/).filter((e=>e.trim().length>0));for(const t of s){t.trim().split(/\s+/).length>20&&o.push(e+1)}}a.length>0&&(t[i.CONTENT.PARAGRAPH_TOO_LONG]={value:!0,additional:a}),o.length>0&&(t[i.CONTENT.SENTENCE_TOO_LONG]={value:!0,additional:o});const r=S(Array.from(s).map((e=>e.textContent?.trim())).filter(Boolean).join(' '));return'sv'===n?t[i.CONTENT.LIX]={value:r.lix}:(t[i.CONTENT.FLESCH_EASE]={value:r.fleschEase},t[i.CONTENT.FLESCH_KINCAID]={value:r.fleschKincaid},t[i.CONTENT.GUNNING_FOG]={value:r.gunningFog},t[i.CONTENT.COLEMAN_LIAU]={value:r.colemanLiau}),t[i.CONTENT.AVERAGE_WORDS_PER_SENTENCE]={value:r.averageWordsPerSentence,additional:r.totalSentences},'sv'===n?t[i.CONTENT.LONG_WORDS]={value:r.longWords,additional:r.totalWords}:t[i.CONTENT.COMPLEX_WORDS]={value:r.complexWords,additional:r.totalWords},t}const p=4,f=8,O=32,T=64;let N;const w=e=>{e?.bucket?.insightsEnabled&&(clearTimeout(N),N=setTimeout((()=>(e=>{const t=e.draft??e.model,s=document.querySelector('title')?.textContent??'',o=document.querySelector('meta[name="description"]')?.getAttribute('content')||'',r=t?.serp?.keywords??'',i={seo:{title:c(s),metaDescription:l(o),keywords:u(document,r)},content:m(document)};a.instance.send({cmd:n,updates:[{action:T,context:{name:window.name,timeStamp:(new Date).toJSON(),insights:i}}]})})(e)),1e3))};let R=!1,I={},y={},C=[];const D=[],_=({data:e})=>{try{e.cmd===s&&e.sync.forEach((e=>{if(e.currentPath===window.location.pathname)switch(e.action){case f:D.forEach((({self:t,handler:n})=>{const s=(e.data.placeholders??[]).find((e=>e.propertyName===t.dataset.field));s&&(t.dataset.placeholder=s.placeholder)})),C=[...e.data?.placeholder??[]],e.context&&(y={...e.context}),w(y);break;case O:const t=e.data?.change;t?D.forEach((({self:n,handler:s})=>{t.name===n.dataset.field&&s(t.value,e.context)})):e.data?.state&&D.forEach((({self:t,handler:n})=>{const s=o(t.dataset.field,e.data.state);void 0!==s&&n(s,e.context)})),e.data?.state&&(I={...e.data.state},R=!0),e.context&&(y={...e.context}),w(y)}}))}catch(e){console.error(e)}},A=(e,t)=>{const n={self:e,handler:t};if(D.push(n),R){const n=o(e.dataset.field,I);void 0!==n&&t(n,y)}if(C.length){const t=C.find((t=>t.propertyName===e.dataset.field));t&&(e.dataset.placeholder=t.placeholder||'')}return()=>{const e=D.indexOf(n);e>-1&&D.splice(e,1)}},L=e=>{if('function'!=typeof e)throw new Error('messageHandler must be a function!');return R&&e(I),a.instance.subscribe((t=>{try{if(t.data.cmd===s)for(const n of t.data.sync)n.action!==O||e(n.data.state)}catch(e){console.error('Error in messageHandler:',e)}}))},v=()=>{const e=((e,t)=>{let n;return function(...s){clearTimeout(n),n=setTimeout((()=>e.apply(this,s)),t)}})((()=>{a.instance.send({cmd:n,updates:[{action:p,context:{name:window.name,height:document.body.scrollHeight}}]})}),100);new ResizeObserver((t=>{for(let n of t)n.target===document.body&&e()})).observe(document.body)};'undefined'!=typeof document&&document.addEventListener('DOMContentLoaded',(e=>{performance.mark('mark-2'),performance.measure('Import elements started','mark-1','mark-2'),console.debug(`${performance.now().toFixed(1)}ms: [${window.name}] Import elements started after ${performance.getEntriesByName('Import elements started')[0].duration.toFixed(1)}ms`),import('./index-DohBRVYp.js'),a.instance.invoke(),a.instance.subscribe(_),v()}));export{o as p,L as s,A as u};
|
|
2
|
-
//# sourceMappingURL=index-
|
|
1
|
+
const e=1,t=2,n=4,s=8;class a extends MessageChannel{static _instanceCache;#e=crypto.randomUUID();#t=[];#n;#s=null;#a=null;#o=null;#r=null;static get instance(){return this._instanceCache||(this._instanceCache=new a),this._instanceCache}constructor(){super(),window.__strifeInstances?(window.__strifeInstances++,console.warn(`[${window.name}] ⚠️ MULTIPLE SubscribableChannel instances detected (${window.__strifeInstances})!`),console.warn(`[${window.name}] 🔄 Please do a HARD REFRESH (Cmd+Shift+R / Ctrl+Shift+R) to clear cached SDK code`)):window.__strifeInstances=1,this.#n=new BroadcastChannel('app.broadcast')}invoke(){switch(this.port1.addEventListener('message',(t=>{t.data.cmd===e&&this.onConnected(t)}),{once:!0}),this.port1.start(),this._ready=new Promise(((e,t)=>{this.readyResolve=e,this.readyReject=t})),this._ready.then((()=>{try{window.top.postMessage({cmd:t,context:{name:window.name,height:document.body.scrollHeight,path:window.location.pathname}},'*',[this.port2])}catch(e){console.error(`[${window.name}] ❌ Failed to send HSHK:`,e),this.readyReject(e)}})),document.readyState){case'loading':case'interactive':document.onreadystatechange=()=>{'complete'===document.readyState&&this.readyResolve()};break;case'complete':this.readyResolve()}}subscribe(e){if('function'!=typeof e)throw new Error('messageHandler must be a function!');if(this.#t.push(e),null===this.#s){this.#s=e=>{this.#o=e,null===this.#r&&(this.#r=requestAnimationFrame((()=>{this.#r=null;const e=this.#o;if(this.#o=null,e)for(const t of this.#t)try{t(e)}catch(e){console.error(`[${window.name}] Error in subscriber:`,e)}})))},this.#a=e=>{try{this.#n.postMessage({...e.data,_sourceInstanceId:this.#e,_sourceType:'iframe',_sourceName:window.name})}catch(e){console.error(`[${window.name}] Error in handleBroadcastMessage:`,e)}};const e=e=>{try{if(e.data._sourceInstanceId===this.#e)return;const{_sourceInstanceId:t,_sourceType:n,_sourceName:s,...a}=e.data;if(a.sync&&Array.isArray(a.sync)){const e=a.sync.filter((e=>!e.currentPath||e.currentPath===window.location.pathname));if(0===e.length)return;a.sync=e}const o={...e,data:a};for(const e of this.#t)try{e(o)}catch(e){console.error(`[${window.name}] Error in subscriber:`,e)}}catch(e){console.error(`[${window.name}] Error in handleBroadcastReceived:`,e)}};this.#n.addEventListener('message',e),this.port1.addEventListener('message',this.#s)}return()=>{const t=this.#t.indexOf(e);t>-1&&this.#t.splice(t,1)}}send(e){this.port1.postMessage(e),this.#n.postMessage({...e,_sourceInstanceId:this.#e,_sourceType:'iframe',_sourceName:window.name})}onConnected(e){return e}}const o=(e,t)=>e?.split('.').reduce(((e,t)=>e?.[t]),t),r=['|','-','–','—',':'],i={SEO:{TITLE:{MISSING:'titleMissing',LENGTH:'titleLength',SEPARATORS:'titleSeparators',SEGMENTS:'titleSegments'},META_DESCRIPTION:{MISSING:'metaDescriptionMissing',LENGTH:'metaDescriptionLength'},KEYWORDS:{COUNT:'keywordCount',DENSITY:'keywordDensity',TITLE:'keywordTitle',META_DESCRIPTION:'keywordMetaDescription',URL:'keywordUrl',HEADINGS:'keywordHeadings',FIRST_PARAGRAPH:'keyword1stParagraph',DISTINCT:'keywordDistinct'}},CONTENT:{PARAGRAPH_TOO_LONG:'contentParagraphTooLong',SENTENCE_TOO_LONG:'contentSentenceTooLong',LIX:'contentLix',FLESCH_EASE:'contentFleschEase',FLESCH_KINCAID:'contentFleschKincaid',GUNNING_FOG:'contentGunningFog',COLEMAN_LIAU:'contentColemanLiau',LONG_WORDS:'contentLongWords',COMPLEX_WORDS:'contentComplexWords',AVERAGE_WORDS_PER_SENTENCE:'contentAverageWordsPerSentence'}};function c(e){const t={};t[i.SEO.TITLE.MISSING]={value:0===e.length},t[i.SEO.TITLE.LENGTH]={value:e.length};const n=function(e){const t=r.find((t=>e.includes(t)));return t?{hasSeparator:!0,segments:e.split(t).map((e=>e.trim())),separator:t}:{hasSeparator:!1,segments:[e],separator:null}}(e);return t[i.SEO.TITLE.SEPARATORS]={value:n.hasSeparator},t[i.SEO.TITLE.SEGMENTS]={value:n.segments.length},t}function l(e){const t={};return t[i.SEO.META_DESCRIPTION.MISSING]={value:0===e.length},t[i.SEO.META_DESCRIPTION.LENGTH]={value:e.length},t}function d(e){return e.toLowerCase().replace(/[.,/#!$%^&*;:{}=\-_`~()]/g,'').replace(/\s+/g,' ').trim()}function h(e,t){const n=d(e),s=d(t),a=n.split(' '),o=s.split(' '),r=[];if(1===o.length){const t=new RegExp(`\\b${i=s,i.replace(/[.*+?^${}()|[\]\\]/g,'\\$&')}\\b`,'gi');return e.match(t)||[]}var i;for(let t=0;t<=a.length-o.length;t++){if(a.slice(t,t+o.length).join(' ')===s){const n=e.split(/\s+/).slice(t,t+o.length).join(' ');r.push(n)}}return r}function u(e,t){let n={};if(!t.trim())return n;const s=t.split(',').map((e=>e.trim())).filter((e=>e.length>0));return s.forEach(((t,s)=>{const a=function(e,t){const n=e.body.textContent||'',s=d(n).split(/\s+/).length,a=h(n,t),o=a.length,r=t.split(/\s+/).length,i=o*r/s*100,c=e.querySelector('title')?.textContent||'',l=h(c,t).length>0,u=e.querySelector('p')?.textContent||'',E=h(u,t).length>0,S=Array.from(e.querySelectorAll('h1')).reduce(((e,n)=>e+h(n.textContent||'',t).length),0),g=Array.from(e.querySelectorAll('h2')).reduce(((e,n)=>e+h(n.textContent||'',t).length),0),p=Array.from(e.querySelectorAll('h3')).reduce(((e,n)=>e+h(n.textContent||'',t).length),0),f=e.querySelector('meta[name="description"]')?.getAttribute('content')||'',O=h(f,t).length>0,m=e.location?.pathname||'',T=d(t).replace(/\s+/g,'-'),N=d(m).includes(T);return{density:i,count:o,inTitle:l,inFirstParagraph:E,inHeadings:{h1:S,h2:g,h3:p},inMetaDescription:O,inUrl:N,occurrences:a}}(e,t);!function(e,t,n){e[i.SEO.KEYWORDS.COUNT]||(e[i.SEO.KEYWORDS.COUNT]=[]);e[i.SEO.KEYWORDS.COUNT].push({value:t.count,additional:{keyword:n}}),e[i.SEO.KEYWORDS.DENSITY]||(e[i.SEO.KEYWORDS.DENSITY]=[]);e[i.SEO.KEYWORDS.DENSITY].push({value:t.density,additional:{keyword:n}}),e[i.SEO.KEYWORDS.TITLE]||(e[i.SEO.KEYWORDS.TITLE]=[]);e[i.SEO.KEYWORDS.TITLE].push({value:t.inTitle,additional:{keyword:n}}),e[i.SEO.KEYWORDS.HEADINGS]||(e[i.SEO.KEYWORDS.HEADINGS]=[]);e[i.SEO.KEYWORDS.HEADINGS].push({value:t.inHeadings.h1+t.inHeadings.h2+t.inHeadings.h3,additional:{keyword:n}}),e[i.SEO.KEYWORDS.FIRST_PARAGRAPH]||(e[i.SEO.KEYWORDS.FIRST_PARAGRAPH]=[]);e[i.SEO.KEYWORDS.FIRST_PARAGRAPH].push({value:t.inFirstParagraph,additional:{keyword:n}}),e[i.SEO.KEYWORDS.META_DESCRIPTION]||(e[i.SEO.KEYWORDS.META_DESCRIPTION]=[]);e[i.SEO.KEYWORDS.META_DESCRIPTION].push({value:t.inMetaDescription,additional:{keyword:n}}),e[i.SEO.KEYWORDS.URL]||(e[i.SEO.KEYWORDS.URL]=[]);e[i.SEO.KEYWORDS.URL].push({value:t.inUrl,additional:{keyword:n}})}(n,a,t)})),s.length>1&&function(e,t){e[i.SEO.KEYWORDS.DISTINCT]||(e[i.SEO.KEYWORDS.DISTINCT]=[]);const n=[];for(let s=0;s<t.length;s++)for(let a=s+1;a<t.length;a++){const o=E(t[s],t[a]);o>.3&&e[i.SEO.KEYWORDS.DISTINCT].push({value:0===n.length,additional:{similarities:[t[s],t[a],o]}})}}(n,s),n}function E(e,t){const n=new Set(e.toLowerCase().split(' ')),s=new Set(t.toLowerCase().split(' ')),a=new Set([...n].filter((e=>s.has(e)))),o=new Set([...n,...s]);return a.size/o.size}function S(e,t){const n=e.split(/\s+/).filter((e=>e.length>0)),s=e.split(/[.!?]+/).filter((e=>e.trim().length>0)),a=function(e){const t=e.toLowerCase().split(/\s+/);return t.reduce(((e,t)=>e+g(t)),0)}(e),o=n.filter((e=>g(e)>2)).length,r=n.length,i=s.length,c=r/i,l=a/r,d=e.replace(/\s/g,'').length/r,h=function(e){const t=e.split(/\s+/).filter((e=>e.length>0)),n=e.split(/[.!?]+/).filter((e=>e.trim().length>0)),s=t.filter((e=>e.length>6)).length;return t.length/n.length+100*s/t.length}(e);return{fleschEase:206.835-1.015*c-84.6*l,fleschKincaid:.39*c+11.8*l-15.59,gunningFog:.4*(c+o/r*100),colemanLiau:100*d*.0588-i/r*100*.296-15.8,averageWordsPerSentence:c,averageSyllablesPerWord:l,totalWords:r,totalSentences:i,complexWords:o,lix:h,longWords:n.filter((e=>e.length>15)).length}}function g(e){if((e=e.toLowerCase().replace(/[^a-z]/g,'')).length<=3)return 1;const t=(e=(e=e.replace(/(?:[^laeiouy]es|ed|[^laeiouy]e)$/,'')).replace(/^y/,'')).match(/[aeiouy]{1,2}/g);return t?t.length:1}function p(e){const t={},n=e.documentElement.lang.toLowerCase().split('-')[0]||'en',s=e.querySelectorAll('p');if(0===s.length)return;const a=[],o=[];for(const[e,t]of Array.from(s).entries()){const n=t.textContent?.trim()||'';if(0===n.length)continue;n.split(/\s+/).filter((e=>e.length>0)).length>40&&a.push(e+1);const s=n.split(/[.!?]+/).filter((e=>e.trim().length>0));for(const t of s){t.trim().split(/\s+/).length>20&&o.push(e+1)}}a.length>0&&(t[i.CONTENT.PARAGRAPH_TOO_LONG]={value:!0,additional:a}),o.length>0&&(t[i.CONTENT.SENTENCE_TOO_LONG]={value:!0,additional:o});const r=S(Array.from(s).map((e=>e.textContent?.trim())).filter(Boolean).join(' '));return'sv'===n?t[i.CONTENT.LIX]={value:r.lix}:(t[i.CONTENT.FLESCH_EASE]={value:r.fleschEase},t[i.CONTENT.FLESCH_KINCAID]={value:r.fleschKincaid},t[i.CONTENT.GUNNING_FOG]={value:r.gunningFog},t[i.CONTENT.COLEMAN_LIAU]={value:r.colemanLiau}),t[i.CONTENT.AVERAGE_WORDS_PER_SENTENCE]={value:r.averageWordsPerSentence,additional:r.totalSentences},'sv'===n?t[i.CONTENT.LONG_WORDS]={value:r.longWords,additional:r.totalWords}:t[i.CONTENT.COMPLEX_WORDS]={value:r.complexWords,additional:r.totalWords},t}const f=4,O=8,m=32,T=64;let N;const R=e=>{e?.bucket?.insightsEnabled&&(clearTimeout(N),N=setTimeout((()=>(e=>{const t=e.draft??e.model,s=document.querySelector('title')?.textContent??'',o=document.querySelector('meta[name="description"]')?.getAttribute('content')||'',r=t?.serp?.keywords??'',i={seo:{title:c(s),metaDescription:l(o),keywords:u(document,r)},content:p(document)};a.instance.send({cmd:n,updates:[{action:T,context:{name:window.name,timeStamp:(new Date).toJSON(),insights:i}}]})})(e)),1e3))};let w=!1,y={},I={},C=[];const D=[],_=({data:e})=>{try{e.cmd===s&&e.sync.forEach((e=>{if(e.currentPath===window.location.pathname)switch(e.action){case O:D.forEach((({self:t,handler:n})=>{const s=(e.data.placeholders??[]).find((e=>e.propertyName===t.dataset.field));s&&(t.dataset.placeholder=s.placeholder)})),C=[...e.data?.placeholder??[]],e.context&&(I={...e.context}),R(I);break;case m:const t=e.data?.change;t?D.forEach((({self:n,handler:s})=>{t.name===n.dataset.field&&s(t.value,e.context)})):e.data?.state&&D.forEach((({self:t,handler:n})=>{const s=o(t.dataset.field,e.data.state);void 0!==s&&n(s,e.context)})),e.data?.state&&(y={...e.data.state},w=!0),e.context&&(I={...e.context}),R(I)}}))}catch(e){console.error(e)}},A=(e,t)=>{const n={self:e,handler:t};if(D.push(n),w){const n=o(e.dataset.field,y);void 0!==n&&t(n,I)}if(C.length){const t=C.find((t=>t.propertyName===e.dataset.field));t&&(e.dataset.placeholder=t.placeholder||'')}return()=>{const e=D.indexOf(n);e>-1&&D.splice(e,1)}},L=e=>{if('function'!=typeof e)throw new Error('messageHandler must be a function!');return w&&e(y),a.instance.subscribe((t=>{try{if(t.data.cmd===s)for(const n of t.data.sync)n.action!==m||e(n.data.state)}catch(e){console.error('Error in messageHandler:',e)}}))},v=()=>{const e=((e,t)=>{let n;return function(...s){clearTimeout(n),n=setTimeout((()=>e.apply(this,s)),t)}})((()=>{a.instance.send({cmd:n,updates:[{action:f,context:{name:window.name,height:document.body.scrollHeight}}]})}),100);new ResizeObserver((t=>{for(let n of t)n.target===document.body&&e()})).observe(document.body)};'undefined'!=typeof document&&document.addEventListener('DOMContentLoaded',(e=>{import('./index-Crin6Dn6.js'),a.instance.invoke(),a.instance.subscribe(_),v()}));export{o as p,L as s,A as u};
|
|
2
|
+
//# sourceMappingURL=index-BIjDe1U1.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index-Cng38i9R.js","sources":["../cmd.js","../subscribableChannel.js","../../../functions/propertyStringToValue.js","../insights/constants.js","../insights/analyzers/seoAnalyzer.js","../insights/analyzers/titleAnalyzer.js","../insights/analyzers/keywordAnalyzer.js","../insights/analyzers/contentAnalyzer.js","../action.js","../insights/index.js","../strife.js"],"sourcesContent":["const CMD = {\n // HSHK: 1,\n // EU: 2,\n // SYNC: 4,\n // CONNECT: 8,\n\n CONNECT: 1,\n HSHK: 2,\n EU: 4,\n SYNC: 8,\n};\n\nexport default CMD;\n","import CMD from './cmd.js';\n\nconst CHANNEL_NAME = 'app.broadcast';\n\nexport default class SubscribableChannel extends MessageChannel {\n static _instanceCache;\n #instanceId = crypto.randomUUID(); // Unique ID per iframe\n #subscribers = []; // Track all subscriber handlers\n #broadcastChannel;\n #handleMessage = null;\n #handleBroadcastMessage = null;\n // Frame-coalesced delivery for parent-port messages: drop older queued events\n // and only run the subscriber loop once per animation frame with the latest\n // event. Without this, a multi-subscriber Svelte site (each component doing\n // `page = data`) saturates the iframe main thread under continuous parent\n // broadcasts (typing/drag), and the preview falls progressively behind.\n #pendingMessageEvent = null;\n #flushRaf = null;\n\n static get instance() {\n if (!this._instanceCache) {\n this._instanceCache = new SubscribableChannel();\n }\n\n return this._instanceCache;\n }\n\n constructor() {\n super(); // Initialize MessageChannel (port1, port2)\n\n // Check for stale instances (HMR/cache issue detection)\n if (window.__strifeInstances) {\n window.__strifeInstances++;\n console.warn(`[${window.name}] ⚠️ MULTIPLE SubscribableChannel instances detected (${window.__strifeInstances})!`);\n console.warn(`[${window.name}] 🔄 Please do a HARD REFRESH (Cmd+Shift+R / Ctrl+Shift+R) to clear cached SDK code`);\n } else {\n window.__strifeInstances = 1;\n }\n\n // BroadcastChannel for iframe-to-iframe communication (same origin)\n this.#broadcastChannel = new BroadcastChannel(CHANNEL_NAME);\n }\n\n /**\n * Initialize the channel - send HSHK to parent with port2\n */\n invoke() {\n // Listen for CONNECT acknowledgment from parent on port1\n const handleConnect = (event) => {\n if (event.data.cmd === CMD.CONNECT) {\n this.onConnected(event);\n }\n };\n this.port1.addEventListener('message', handleConnect, {\n once: true,\n });\n this.port1.start();\n\n this._ready = new Promise((resolve, reject) => {\n this.readyResolve = resolve;\n this.readyReject = reject;\n });\n\n // Wait for document ready, then send HSHK to parent\n this._ready.then(() => {\n try {\n window.top.postMessage(\n {\n cmd: CMD.HSHK,\n context: {\n name: window.name,\n height: document.body.scrollHeight,\n path: window.location.pathname\n }\n },\n '*', // targetOrigin (parent's origin)\n [this.port2] // Transfer port2 to parent\n );\n } catch (error) {\n console.error(`[${window.name}] ❌ Failed to send HSHK:`, error);\n this.readyReject(error);\n }\n });\n\n switch (document.readyState) {\n case 'loading':\n case 'interactive': {\n document.onreadystatechange = () => {\n if (document.readyState === 'complete') {\n this.readyResolve();\n }\n };\n break;\n }\n case 'complete':\n this.readyResolve();\n break;\n }\n }\n\n /**\n * Subscribe to messages from parent or other iframes\n * @param {Function} messageHandler - Called when a message is received\n * @returns {Function} Unsubscribe function\n */\n subscribe(messageHandler) {\n if (typeof messageHandler !== 'function') {\n throw new Error('messageHandler must be a function!');\n }\n\n // Add this handler to the subscribers list\n this.#subscribers.push(messageHandler);\n\n // Set up listeners ONLY ONCE on first subscription\n if (this.#handleMessage === null) {\n // Handler for messages from parent via MessageChannel port1.\n // Coalesces to one subscriber-loop per animation frame so a 60 Hz parent\n // broadcast (drag/typing) doesn't queue up an unbounded backlog of\n // Svelte-cascade work in the iframe. Always delivers the LATEST event.\n this.#handleMessage = (event) => {\n this.#pendingMessageEvent = event;\n if (this.#flushRaf !== null) return;\n this.#flushRaf = requestAnimationFrame(() => {\n this.#flushRaf = null;\n const ev = this.#pendingMessageEvent;\n this.#pendingMessageEvent = null;\n if (!ev) return;\n for (const subscriber of this.#subscribers) {\n try {\n subscriber(ev);\n } catch (error) {\n console.error(`[${window.name}] Error in subscriber:`, error);\n }\n }\n });\n };\n\n // Forward messages from parent to sibling iframes via BroadcastChannel\n this.#handleBroadcastMessage = (event) => {\n try {\n // Tag with instance ID before broadcasting\n this.#broadcastChannel.postMessage({\n ...event.data,\n _sourceInstanceId: this.#instanceId,\n _sourceType: 'iframe',\n _sourceName: window.name\n });\n } catch (error) {\n console.error(`[${window.name}] Error in handleBroadcastMessage:`, error);\n }\n };\n\n // Handler for messages from sibling iframes via BroadcastChannel\n const handleBroadcastReceived = (event) => {\n try {\n const isSelf = event.data._sourceInstanceId === this.#instanceId;\n\n // Skip messages from self\n if (isSelf) {\n return;\n }\n\n // Prepare clean data (remove metadata)\n const { _sourceInstanceId, _sourceType, _sourceName, ...data } = event.data;\n\n // Filter sync updates by current path if applicable\n if (data.sync && Array.isArray(data.sync)) {\n const filteredSync = data.sync.filter(update => {\n // If update specifies a path, only process if it matches our current path\n if (update.currentPath) {\n return update.currentPath === window.location.pathname;\n }\n // No path specified, process it\n return true;\n });\n\n // If no updates match our path, skip this message entirely\n if (filteredSync.length === 0) {\n return;\n }\n\n // Replace sync array with filtered version\n data.sync = filteredSync;\n }\n\n const cleanEvent = { ...event, data };\n\n // Call ALL subscribers with the filtered data\n for (const subscriber of this.#subscribers) {\n try {\n subscriber(cleanEvent);\n } catch (error) {\n console.error(`[${window.name}] Error in subscriber:`, error);\n }\n }\n } catch (error) {\n console.error(`[${window.name}] Error in handleBroadcastReceived:`, error);\n }\n };\n\n // Add listeners ONCE\n this.#broadcastChannel.addEventListener('message', handleBroadcastReceived);\n this.port1.addEventListener('message', this.#handleMessage);\n\n // INTENTIONALLY DISABLED: This line caused 3× message amplification (67% excess handler calls)\n //\n // Architecture Decision:\n // Parent messages are now sent directly to ALL iframes via their individual MessageChannel\n // ports (see MessageService.postMessage). BroadcastChannel is ONLY for iframe-to-iframe\n // communication (e.g., height updates), not for forwarding parent messages.\n //\n // The Problem (when enabled):\n // 1. Parent sends SYNC to Desktop iframe via MessageChannel\n // 2. Desktop's handleBroadcastMessage forwards to BroadcastChannel\n // 3. Desktop receives its OWN broadcast (in addition to the direct message)\n // 4. Result: Each iframe processes parent messages 3× (1 direct + 2 sibling broadcasts)\n //\n // DO NOT re-enable without solving the amplification issue.\n //\n // this.port1.addEventListener('message', this.#handleBroadcastMessage);\n }\n\n // Return unsubscribe function\n return () => {\n const index = this.#subscribers.indexOf(messageHandler);\n if (index > -1) {\n this.#subscribers.splice(index, 1);\n }\n };\n }\n\n /**\n * Send a message to parent and siblings\n * @param {Object} payload - Message to send\n */\n send(payload) {\n // Send to parent via MessageChannel port1\n this.port1.postMessage(payload);\n\n // Also broadcast to siblings via BroadcastChannel (tagged with instanceId)\n this.#broadcastChannel.postMessage({\n ...payload,\n _sourceInstanceId: this.#instanceId,\n _sourceType: 'iframe',\n _sourceName: window.name\n });\n }\n\n onConnected(event) {\n return event;\n }\n}\n","export const propertyStringToValue = (propertyString, model) => {\n return propertyString?.split('.').reduce((a, b) => a?.[b], model);\n};","export const TITLE_SEPARATORS = ['|', '-', '–', '—', ':'];\nexport const BRAND_POSITION_END = 'end';\n\nexport const SEO_RULES = {\n TITLE_LENGTH: {\n MIN: 50,\n MAX: 60\n },\n META_DESCRIPTION_LENGTH: {\n MIN: 120,\n MAX: 155\n }\n};\n\nexport const INSIGHTS_IMPACT = {\n ERROR: 'error',\n WARN: 'warn',\n SUCCESS: 'success',\n INFO: 'info'\n};\n\nexport const INSIGHTS_METRICS = {\n SEO: {\n TITLE: {\n MISSING: 'titleMissing',\n LENGTH: 'titleLength',\n SEPARATORS: 'titleSeparators',\n SEGMENTS: 'titleSegments',\n },\n META_DESCRIPTION: {\n MISSING: 'metaDescriptionMissing',\n LENGTH: 'metaDescriptionLength',\n },\n KEYWORDS: {\n COUNT: 'keywordCount',\n DENSITY: 'keywordDensity',\n TITLE: 'keywordTitle',\n META_DESCRIPTION: 'keywordMetaDescription',\n URL: 'keywordUrl',\n HEADINGS: 'keywordHeadings',\n FIRST_PARAGRAPH: 'keyword1stParagraph',\n DISTINCT: 'keywordDistinct',\n },\n },\n CONTENT: {\n PARAGRAPH_TOO_LONG: 'contentParagraphTooLong',\n SENTENCE_TOO_LONG: 'contentSentenceTooLong',\n LIX: 'contentLix',\n FLESCH_EASE: 'contentFleschEase',\n FLESCH_KINCAID: 'contentFleschKincaid',\n GUNNING_FOG: 'contentGunningFog',\n COLEMAN_LIAU: 'contentColemanLiau',\n LONG_WORDS: 'contentLongWords',\n COMPLEX_WORDS: 'contentComplexWords',\n AVERAGE_WORDS_PER_SENTENCE: 'contentAverageWordsPerSentence',\n },\n}\n\n\n// TITLE_MISSING: 'titleMissing',\n// TITLE_LENGTH: 'titleLength',\n// TITLE_SEPARATORS: 'titleSeparators',\n// TITLE_SEGMENTS: 'titleSegments',\n// META_DESCRIPTION_MISSING: 'metaDescriptionMissing',\n// META_DESCRIPTION_LENGTH: 'metaDescriptionLength',\n// KEYWORD_COUNT: 'keywordCount',\n// KEYWORD_DENSITY: 'keywordDensity',\n// KEYWORD_TITLE: 'keywordTitle',\n// KEYWORD_META_DESCRIPTION: 'keywordMetaDescription',\n// KEYWORD_URL: 'keywordUrl',\n// KEYWORD_HEADINGS: 'keywordHeadings',\n// KEYWORD_1ST_PARAGRAPH: 'keyword1stParagraph',\n// KEYWORD_DISTINCT: 'keywordDistinct',\n// CONTENT_PARAGRAPH_TOO_LONG: 'contentParagraphTooLong',\n// CONTENT_SENTENCE_TOO_LONG: 'contentSentenceTooLong',\n// CONTENT_LIX: 'contentLix',\n// CONTENT_FLESCH_EASE: 'contentFleschEase',\n// CONTENT_FLESCH_KINCAID: 'contentFleschKincaid',\n// CONTENT_GUNNING_FOG: 'contentGunningFog',\n// CONTENT_COLEMAN_LIAU: 'contentColemanLiau',\n// CONTENT_LONG_WORDS: 'contentLongWords',\n// CONTENT_COMPLEX_WORDS: 'contentComplexWords',\n// CONTENT_AVERAGE_WORDS_PER_SENTENCE: 'contentAverageWordsPerSentence',","import { INSIGHTS_METRICS } from '../constants.js';\nimport { analyzeTitleFormat } from './titleAnalyzer.js';\n\nexport function analyzeTitle(title) {\n const results = {};\n\n results[INSIGHTS_METRICS.SEO.TITLE.MISSING] = { value: title.length === 0 };\n results[INSIGHTS_METRICS.SEO.TITLE.LENGTH] = { value: title.length };\n\n // Format analysis\n const titleAnalysis = analyzeTitleFormat(title);\n\n results[INSIGHTS_METRICS.SEO.TITLE.SEPARATORS] = { value: titleAnalysis.hasSeparator };\n results[INSIGHTS_METRICS.SEO.TITLE.SEGMENTS] = { value: titleAnalysis.segments.length };\n\n return results;\n}\n\nexport function analyzeMetaDescription(metaDescription) {\n const results = {};\n\n results[INSIGHTS_METRICS.SEO.META_DESCRIPTION.MISSING] = { value: metaDescription.length === 0 };\n results[INSIGHTS_METRICS.SEO.META_DESCRIPTION.LENGTH] = { value: metaDescription.length };\n\n return results;\n}","import { TITLE_SEPARATORS } from '../constants.js';\n\nexport function analyzeTitleFormat(title) {\n const usedSeparator = TITLE_SEPARATORS.find(sep => title.includes(sep));\n\n if (!usedSeparator) {\n return {\n hasSeparator: false,\n segments: [title],\n separator: null\n };\n }\n\n const segments = title.split(usedSeparator).map(s => s.trim());\n return {\n hasSeparator: true,\n segments,\n separator: usedSeparator\n };\n}","import { INSIGHTS_METRICS } from '../constants.js';\n\nfunction escapeRegExp(string) {\n return string.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nfunction normalizeText(text) {\n return text\n .toLowerCase()\n .replace(/[.,/#!$%^&*;:{}=\\-_`~()]/g, '') // Remove punctuation\n .replace(/\\s+/g, ' ') // Normalize whitespace\n .trim();\n}\n\nfunction findKeywordOccurrences(text, keyword) {\n const normalizedText = normalizeText(text);\n const normalizedKeyword = normalizeText(keyword);\n const words = normalizedText.split(' ');\n const keywordWords = normalizedKeyword.split(' ');\n const occurrences = [];\n\n if (keywordWords.length === 1) {\n const regex = new RegExp(`\\\\b${escapeRegExp(normalizedKeyword)}\\\\b`, 'gi');\n const matches = text.match(regex);\n return matches || [];\n }\n\n for (let i = 0; i <= words.length - keywordWords.length; i++) {\n const possibleMatch = words.slice(i, i + keywordWords.length).join(' ');\n if (possibleMatch === normalizedKeyword) {\n const originalTextMatch = text\n .split(/\\s+/)\n .slice(i, i + keywordWords.length)\n .join(' ');\n occurrences.push(originalTextMatch);\n }\n }\n\n return occurrences;\n}\n\nfunction countKeywordInText(text, keyword) {\n return findKeywordOccurrences(text, keyword).length;\n}\n\nexport function analyzeKeywordUsage(document, keywordsInput) {\n let results = {};\n\n if (!keywordsInput.trim()) {\n return results;\n }\n\n const keywords = keywordsInput\n .split(',')\n .map((k) => k.trim())\n .filter((k) => k.length > 0);\n\n keywords.forEach((keyword, index) => {\n const analysis = analyzeKeyword(document, keyword);\n displayResults(results, analysis, keyword);\n });\n\n if (keywords.length > 1) {\n analyzeKeywordRelationships(results, keywords);\n }\n\n return results;\n}\n\nfunction analyzeKeyword(document, keyword) {\n const bodyText = document.body.textContent || '';\n const wordCount = normalizeText(bodyText).split(/\\s+/).length;\n const occurrences = findKeywordOccurrences(bodyText, keyword);\n const keywordCount = occurrences.length;\n const keywordWordCount = keyword.split(/\\s+/).length;\n const density = ((keywordCount * keywordWordCount) / wordCount) * 100;\n\n const title = document.querySelector('title')?.textContent || '';\n const inTitle = findKeywordOccurrences(title, keyword).length > 0;\n\n const firstParagraph = document.querySelector('p')?.textContent || '';\n const inFirstParagraph = findKeywordOccurrences(firstParagraph, keyword).length > 0;\n\n const h1Count = Array.from(document.querySelectorAll('h1')).reduce(\n (count, el) => count + findKeywordOccurrences(el.textContent || '', keyword).length,\n 0,\n );\n const h2Count = Array.from(document.querySelectorAll('h2')).reduce(\n (count, el) => count + findKeywordOccurrences(el.textContent || '', keyword).length,\n 0,\n );\n const h3Count = Array.from(document.querySelectorAll('h3')).reduce(\n (count, el) => count + findKeywordOccurrences(el.textContent || '', keyword).length,\n 0,\n );\n\n const metaDescription = document.querySelector('meta[name=\"description\"]')?.getAttribute('content') || '';\n const inMetaDescription = findKeywordOccurrences(metaDescription, keyword).length > 0;\n\n const url = document.location?.pathname || '';\n const urlKeyword = normalizeText(keyword).replace(/\\s+/g, '-');\n const inUrl = normalizeText(url).includes(urlKeyword);\n\n return {\n density,\n count: keywordCount,\n inTitle,\n inFirstParagraph,\n inHeadings: { h1: h1Count, h2: h2Count, h3: h3Count },\n inMetaDescription,\n inUrl,\n occurrences,\n };\n}\n\nfunction displayResults(results, analysis, keyword) {\n if (!results[INSIGHTS_METRICS.SEO.KEYWORDS.COUNT]) {\n results[INSIGHTS_METRICS.SEO.KEYWORDS.COUNT] = [];\n }\n results[INSIGHTS_METRICS.SEO.KEYWORDS.COUNT].push({ value: analysis.count, additional: { keyword } });\n\n if (!results[INSIGHTS_METRICS.SEO.KEYWORDS.DENSITY]) {\n results[INSIGHTS_METRICS.SEO.KEYWORDS.DENSITY] = [];\n }\n results[INSIGHTS_METRICS.SEO.KEYWORDS.DENSITY].push({ value: analysis.density, additional: { keyword } });\n\n if (!results[INSIGHTS_METRICS.SEO.KEYWORDS.TITLE]) {\n results[INSIGHTS_METRICS.SEO.KEYWORDS.TITLE] = [];\n }\n results[INSIGHTS_METRICS.SEO.KEYWORDS.TITLE].push({ value: analysis.inTitle, additional: { keyword } });\n\n if (!results[INSIGHTS_METRICS.SEO.KEYWORDS.HEADINGS]) {\n results[INSIGHTS_METRICS.SEO.KEYWORDS.HEADINGS] = [];\n }\n results[INSIGHTS_METRICS.SEO.KEYWORDS.HEADINGS].push({\n value: analysis.inHeadings.h1 + analysis.inHeadings.h2 + analysis.inHeadings.h3,\n additional: { keyword },\n });\n\n if (!results[INSIGHTS_METRICS.SEO.KEYWORDS.FIRST_PARAGRAPH]) {\n results[INSIGHTS_METRICS.SEO.KEYWORDS.FIRST_PARAGRAPH] = [];\n }\n results[INSIGHTS_METRICS.SEO.KEYWORDS.FIRST_PARAGRAPH].push({ value: analysis.inFirstParagraph, additional: { keyword } });\n\n if (!results[INSIGHTS_METRICS.SEO.KEYWORDS.META_DESCRIPTION]) {\n results[INSIGHTS_METRICS.SEO.KEYWORDS.META_DESCRIPTION] = [];\n }\n results[INSIGHTS_METRICS.SEO.KEYWORDS.META_DESCRIPTION].push({\n value: analysis.inMetaDescription,\n additional: { keyword },\n });\n\n if (!results[INSIGHTS_METRICS.SEO.KEYWORDS.URL]) {\n results[INSIGHTS_METRICS.SEO.KEYWORDS.URL] = [];\n }\n results[INSIGHTS_METRICS.SEO.KEYWORDS.URL].push({ value: analysis.inUrl, additional: { keyword } });\n}\n\nfunction analyzeKeywordRelationships(results, keywords) {\n if (!results[INSIGHTS_METRICS.SEO.KEYWORDS.DISTINCT]) {\n results[INSIGHTS_METRICS.SEO.KEYWORDS.DISTINCT] = [];\n }\n const similarities = [];\n\n for (let i = 0; i < keywords.length; i++) {\n for (let j = i + 1; j < keywords.length; j++) {\n const similarity = calculateSimilarity(keywords[i], keywords[j]);\n if (similarity > 0.3) {\n results[INSIGHTS_METRICS.SEO.KEYWORDS.DISTINCT].push({\n value: similarities.length === 0,\n additional: { similarities: [keywords[i], keywords[j], similarity] },\n });\n }\n }\n }\n}\n\nfunction calculateSimilarity(str1, str2) {\n const set1 = new Set(str1.toLowerCase().split(' '));\n const set2 = new Set(str2.toLowerCase().split(' '));\n const intersection = new Set([...set1].filter((x) => set2.has(x)));\n const union = new Set([...set1, ...set2]);\n return intersection.size / union.size;\n}\n","import { INSIGHTS_METRICS } from \"../constants.js\";\n\nfunction calculateMetrics(text, language) {\n const words = text.split(/\\s+/).filter(word => word.length > 0);\n const sentences = text.split(/[.!?]+/).filter(sentence => sentence.trim().length > 0);\n const totalSyllables = countSyllables(text);\n const complexWords = words.filter(word => countWordSyllables(word) > 2).length;\n\n const totalWords = words.length;\n const totalSentences = sentences.length;\n const averageWordsPerSentence = totalWords / totalSentences;\n const averageSyllablesPerWord = totalSyllables / totalWords;\n const chars = text.replace(/\\s/g, '').length;\n const averageCharsPerWord = chars / totalWords;\n\n const lix = calculateLIX(text);\n const longWords = words.filter(word => word.length > 15).length;\n\n return {\n fleschEase: 206.835 - (1.015 * averageWordsPerSentence) - (84.6 * averageSyllablesPerWord),\n fleschKincaid: (0.39 * averageWordsPerSentence) + (11.8 * averageSyllablesPerWord) - 15.59,\n gunningFog: 0.4 * (averageWordsPerSentence + 100 * (complexWords / totalWords)),\n colemanLiau: (0.0588 * (averageCharsPerWord * 100)) - (0.296 * (totalSentences / totalWords * 100)) - 15.8,\n averageWordsPerSentence,\n averageSyllablesPerWord,\n totalWords,\n totalSentences,\n complexWords,\n lix,\n longWords\n };\n}\n\nfunction countSyllables(text) {\n const words = text.toLowerCase().split(/\\s+/);\n return words.reduce((total, word) => {\n return total + countWordSyllables(word);\n }, 0);\n}\n\nfunction countWordSyllables(word) {\n word = word.toLowerCase().replace(/[^a-z]/g, '');\n if (word.length <= 3) return 1;\n\n word = word.replace(/(?:[^laeiouy]es|ed|[^laeiouy]e)$/, '');\n word = word.replace(/^y/, '');\n const syllables = word.match(/[aeiouy]{1,2}/g);\n return syllables ? syllables.length : 1;\n}\n\nfunction calculateLIX(text) {\n const words = text.split(/\\s+/).filter(word => word.length > 0);\n const sentences = text.split(/[.!?]+/).filter(sentence => sentence.trim().length > 0);\n const longWords = words.filter(word => word.length > 6).length;\n\n return (words.length / sentences.length) + (longWords * 100 / words.length);\n}\n\nexport function analyzeContent(document) {\n const results = {};\n\n const language = document.documentElement.lang.toLowerCase().split('-')[0] || 'en';\n\n const paragraphs = document.querySelectorAll('p');\n if (paragraphs.length === 0) {\n return;\n }\n\n // Analyze each paragraph individually\n const tooLongParagraphs = [];\n const tooLongSentences = [];\n for (const [index, paragraph] of Array.from(paragraphs).entries()) {\n const text = paragraph.textContent?.trim() || '';\n if (text.length === 0) continue;\n\n const words = text.split(/\\s+/).filter(word => word.length > 0);\n if (words.length > 40) {\n tooLongParagraphs.push(index + 1);\n }\n\n const sentences = text.split(/[.!?]+/).filter(sentence => sentence.trim().length > 0);\n for (const sentence of sentences) {\n const sentenceWords = sentence.trim().split(/\\s+/).length;\n if (sentenceWords > 20) {\n tooLongSentences.push(index + 1);\n }\n }\n }\n\n if (tooLongParagraphs.length > 0) {\n results[INSIGHTS_METRICS.CONTENT.PARAGRAPH_TOO_LONG] = {value: true, additional: tooLongParagraphs};\n }\n if (tooLongSentences.length > 0) {\n results[INSIGHTS_METRICS.CONTENT.SENTENCE_TOO_LONG] = {value: true, additional: tooLongSentences};\n }\n\n // Analyze overall content\n const fullText = Array.from(paragraphs)\n .map(p => p.textContent?.trim())\n .filter(Boolean)\n .join(' ');\n\n const metrics = calculateMetrics(fullText, language);\n\n if (language === 'sv') {\n results[INSIGHTS_METRICS.CONTENT.LIX] = {value: metrics.lix};\n } else {\n results[INSIGHTS_METRICS.CONTENT.FLESCH_EASE] = {value: metrics.fleschEase};\n results[INSIGHTS_METRICS.CONTENT.FLESCH_KINCAID] = {value: metrics.fleschKincaid};\n results[INSIGHTS_METRICS.CONTENT.GUNNING_FOG] = {value: metrics.gunningFog};\n results[INSIGHTS_METRICS.CONTENT.COLEMAN_LIAU] = {value: metrics.colemanLiau};\n }\n\n results[INSIGHTS_METRICS.CONTENT.AVERAGE_WORDS_PER_SENTENCE] = {value: metrics.averageWordsPerSentence, additional: metrics.totalSentences};\n\n if (language === 'sv') {\n results[INSIGHTS_METRICS.CONTENT.LONG_WORDS] = {value: metrics.longWords, additional: metrics.totalWords};\n } else {\n results[INSIGHTS_METRICS.CONTENT.COMPLEX_WORDS] = {value: metrics.complexWords, additional: metrics.totalWords};\n }\n\n return results;\n}\n","// const ACTION = {\n// NONE: 8,\n// EDIT: 16,\n// RESET: 32,\n// INIT: 64,\n// SYNC: 128,\n// STATE: 256,\n// FOCUS: 512,\n// };\n\nconst PREVIEWACTION = {\n SYNC: 4,\n INIT: 8,\n FOCUS: 16,\n UPDATE: 32,\n INSIGHTS: 64,\n};\n\nexport default PREVIEWACTION;\n","import SubscribableChannel from '../subscribableChannel.js';\nimport * as analyzers from './analyzers/index.js';\nimport CMD from '../cmd.js';\nimport PREVIEWACTION from '../action.js';\n\nlet insightsTimeout;\n\nconst sendInsights = (context) => {\n const model = context.draft ?? context.model;\n const title = document.querySelector('title')?.textContent ?? '';\n const metaDesc = document.querySelector('meta[name=\"description\"]')?.getAttribute('content') || '';\n const keywords = model?.serp?.keywords ?? '';\n\n const insights = {\n seo: {\n title: analyzers.analyzeTitle(title),\n metaDescription: analyzers.analyzeMetaDescription(metaDesc),\n keywords: analyzers.analyzeKeywordUsage(document, keywords),\n },\n content: analyzers.analyzeContent(document),\n };\n\n const messageChannel = SubscribableChannel.instance;\n messageChannel.send({\n cmd: CMD.EU,\n updates: [\n { action: PREVIEWACTION.INSIGHTS, context: { name: window.name, timeStamp: new Date().toJSON(), insights } },\n ],\n });\n};\n\nexport const runInsights = (context) => {\n if (!context?.bucket?.insightsEnabled) {\n return;\n }\n clearTimeout(insightsTimeout);\n insightsTimeout = setTimeout(() => sendInsights(context), 1000);\n};\n","import SubscribableChannel from './subscribableChannel.js';\nimport { propertyStringToValue } from '../../functions/propertyStringToValue.js';\nimport { runInsights } from './insights/index.js';\nimport CMD from './cmd.js';\nimport PREVIEWACTION from './action.js';\n\nlet stateInitialized = false;\nlet state = {};\nlet context = {};\nlet placeholders = [];\n\nconst handlers = [];\n\nconst defaultHandler = ({ data }) => {\n try {\n if (data.cmd === CMD.SYNC) {\n data.sync.forEach((update) => {\n if (update.currentPath !== window.location.pathname) {\n return;\n }\n\n switch (update.action) {\n case PREVIEWACTION.INIT:\n handlers.forEach(({ self, handler }) => {\n // Init placeholders\n const currentUpdate = (update.data.placeholders ?? []).find((d) => d.propertyName === self.dataset.field);\n if (currentUpdate) {\n self.dataset.placeholder = currentUpdate.placeholder;\n }\n });\n placeholders = [...(update.data?.placeholder ?? [])];\n if (update.context) {\n context = { ...update.context };\n }\n runInsights(context);\n break;\n case PREVIEWACTION.UPDATE:\n const change = update.data?.change;\n if (change) {\n //If change is provided, only update the field that changed\n handlers.forEach(({ self, handler }) => {\n if (change.name === self.dataset.field) {\n handler(change.value, update.context);\n }\n });\n } else if (update.data?.state) {\n //If only state is provided, update all fields\n handlers.forEach(({ self, handler }) => {\n const value = propertyStringToValue(self.dataset.field, update.data.state);\n if (value !== undefined) {\n handler(value, update.context);\n }\n });\n }\n\n if (update.data?.state) {\n state = { ...update.data.state };\n stateInitialized = true;\n }\n if (update.context) {\n context = { ...update.context };\n }\n runInsights(context);\n break;\n case PREVIEWACTION.FOCUS:\n break;\n }\n });\n }\n } catch (error) {\n console.error(error);\n }\n};\n\nconst useState = (self, handler) => {\n const entry = { self, handler };\n handlers.push(entry);\n\n //If state is already initialized, call handler with current state to initialize with current state\n if (stateInitialized) {\n const value = propertyStringToValue(self.dataset.field, state);\n if (value !== undefined) {\n handler(value, context);\n }\n }\n if (placeholders.length) {\n const placeholderValue = placeholders.find((d) => d.propertyName === self.dataset.field);\n if (placeholderValue) {\n self.dataset.placeholder = placeholderValue.placeholder || '';\n }\n }\n\n // Return cleanup function for disconnectedCallback\n return () => {\n const idx = handlers.indexOf(entry);\n if (idx > -1) handlers.splice(idx, 1);\n };\n};\n\nconst subscribe = (messageHandler) => {\n if (typeof messageHandler !== 'function') {\n throw new Error('messageHandler must be a function!');\n }\n\n const handleMessage = (event) => {\n try {\n // Filter out sync messages containing state updates\n if (event.data.cmd === CMD.SYNC) {\n for (const update of event.data.sync) {\n if (update.action === PREVIEWACTION.UPDATE) {\n messageHandler(update.data.state);\n continue;\n }\n }\n }\n } catch (error) {\n console.error('Error in messageHandler:', error);\n }\n };\n\n //If state is already initialized, call handler with current state to initialize with current state\n if (stateInitialized) {\n messageHandler(state);\n }\n\n return SubscribableChannel.instance.subscribe(handleMessage);\n};\n\nconst initResizeObserver = () => {\n const debounce = (func, wait) => {\n let timeout;\n return function (...args) {\n clearTimeout(timeout);\n timeout = setTimeout(() => func.apply(this, args), wait);\n };\n };\n const sendHeightUpdate = () => {\n const messageChannel = SubscribableChannel.instance;\n messageChannel.send({\n cmd: CMD.EU,\n updates: [{ action: PREVIEWACTION.SYNC, context: { name: window.name, height: document.body.scrollHeight } }],\n });\n };\n const debouncedSendHeightUpdate = debounce(sendHeightUpdate, 100);\n\n const resizeObserver = new ResizeObserver((entries) => {\n for (let entry of entries) {\n if (entry.target === document.body) {\n debouncedSendHeightUpdate();\n }\n }\n });\n\n resizeObserver.observe(document.body);\n};\n\nif (typeof document !== 'undefined') {\n document.addEventListener('DOMContentLoaded', (evt) => {\n performance.mark('mark-2');\n\n performance.measure('Import elements started', 'mark-1', 'mark-2');\n\n console.debug(\n `${performance.now().toFixed(1)}ms: [${window.name}] Import elements started after ${performance\n\n .getEntriesByName('Import elements started')[0]\n .duration.toFixed(1)}ms`,\n );\n\n import('./composition/index.js');\n\n SubscribableChannel.instance.invoke();\n\n SubscribableChannel.instance.subscribe(defaultHandler);\n\n //Add resize observer on document.body to send height to messageChannel\n\n initResizeObserver();\n });\n}\n\nexport { useState, subscribe };\n"],"names":["CMD","SubscribableChannel","MessageChannel","static","instanceId","crypto","randomUUID","subscribers","broadcastChannel","handleMessage","handleBroadcastMessage","pendingMessageEvent","flushRaf","instance","this","_instanceCache","constructor","super","window","__strifeInstances","console","warn","name","BroadcastChannel","invoke","port1","addEventListener","event","data","cmd","onConnected","once","start","_ready","Promise","resolve","reject","readyResolve","readyReject","then","top","postMessage","context","height","document","body","scrollHeight","path","location","pathname","port2","error","readyState","onreadystatechange","subscribe","messageHandler","Error","push","requestAnimationFrame","ev","subscriber","_sourceInstanceId","_sourceType","_sourceName","handleBroadcastReceived","sync","Array","isArray","filteredSync","filter","update","currentPath","length","cleanEvent","index","indexOf","splice","send","payload","propertyStringToValue","propertyString","model","split","reduce","a","b","TITLE_SEPARATORS","INSIGHTS_METRICS","SEO","TITLE","MISSING","LENGTH","SEPARATORS","SEGMENTS","META_DESCRIPTION","KEYWORDS","COUNT","DENSITY","URL","HEADINGS","FIRST_PARAGRAPH","DISTINCT","CONTENT","PARAGRAPH_TOO_LONG","SENTENCE_TOO_LONG","LIX","FLESCH_EASE","FLESCH_KINCAID","GUNNING_FOG","COLEMAN_LIAU","LONG_WORDS","COMPLEX_WORDS","AVERAGE_WORDS_PER_SENTENCE","analyzeTitle","title","results","value","titleAnalysis","usedSeparator","find","sep","includes","hasSeparator","segments","map","s","trim","separator","analyzeTitleFormat","analyzeMetaDescription","metaDescription","normalizeText","text","toLowerCase","replace","findKeywordOccurrences","keyword","normalizedText","normalizedKeyword","words","keywordWords","occurrences","regex","RegExp","string","match","i","slice","join","originalTextMatch","analyzeKeywordUsage","keywordsInput","keywords","k","forEach","analysis","bodyText","textContent","wordCount","keywordCount","keywordWordCount","density","querySelector","inTitle","firstParagraph","inFirstParagraph","h1Count","from","querySelectorAll","count","el","h2Count","h3Count","getAttribute","inMetaDescription","url","urlKeyword","inUrl","inHeadings","h1","h2","h3","analyzeKeyword","additional","displayResults","similarities","j","similarity","calculateSimilarity","analyzeKeywordRelationships","str1","str2","set1","Set","set2","intersection","x","has","union","size","calculateMetrics","language","word","sentences","sentence","totalSyllables","total","countWordSyllables","countSyllables","complexWords","totalWords","totalSentences","averageWordsPerSentence","averageSyllablesPerWord","averageCharsPerWord","lix","longWords","calculateLIX","fleschEase","fleschKincaid","gunningFog","colemanLiau","syllables","analyzeContent","documentElement","lang","paragraphs","tooLongParagraphs","tooLongSentences","paragraph","entries","metrics","p","Boolean","PREVIEWACTION","insightsTimeout","runInsights","bucket","insightsEnabled","clearTimeout","setTimeout","draft","metaDesc","serp","insights","seo","analyzers.analyzeTitle","analyzers.analyzeMetaDescription","analyzers.analyzeKeywordUsage","content","analyzers.analyzeContent","updates","action","timeStamp","Date","toJSON","sendInsights","stateInitialized","state","placeholders","handlers","defaultHandler","self","handler","currentUpdate","d","propertyName","dataset","field","placeholder","change","undefined","useState","entry","placeholderValue","idx","initResizeObserver","debouncedSendHeightUpdate","func","wait","timeout","args","apply","debounce","ResizeObserver","target","observe","evt","performance","mark","measure","debug","now","toFixed","getEntriesByName","duration","import"],"mappings":"AAAA,MAAMA,EAMK,EANLA,EAOE,EAPFA,EAQA,EARAA,EASE,ECLO,MAAMC,UAA4BC,eAC/CC,sBACAC,GAAcC,OAAOC,aACrBC,GAAe,GACfC,GACAC,GAAiB,KACjBC,GAA0B,KAM1BC,GAAuB,KACvBC,GAAY,KAEZ,mBAAWC,GAKT,OAJKC,KAAKC,iBACRD,KAAKC,eAAiB,IAAId,GAGrBa,KAAKC,cACd,CAEA,WAAAC,GACEC,QAGIC,OAAOC,mBACTD,OAAOC,oBACPC,QAAQC,KAAK,IAAIH,OAAOI,8DAA8DJ,OAAOC,uBAC7FC,QAAQC,KAAK,IAAIH,OAAOI,4FAExBJ,OAAOC,kBAAoB,EAI7BL,MAAKN,EAAoB,IAAIe,iBAtCZ,gBAuCnB,CAKA,MA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I,uCAAuC0Q,YAElFM,iBAAiB,2BAA2B,GAC5CC,SAASF,QAAQ,QAGtBG,OAAO,uBAEPvS,EAAoBY,SAASW,SAE7BvB,EAAoBY,SAASyC,UAAU+M,GAIvCe,GAAoB"}
|
|
1
|
+
{"version":3,"file":"index-BIjDe1U1.js","sources":["../cmd.js","../subscribableChannel.js","../../../functions/propertyStringToValue.js","../insights/constants.js","../insights/analyzers/seoAnalyzer.js","../insights/analyzers/titleAnalyzer.js","../insights/analyzers/keywordAnalyzer.js","../insights/analyzers/contentAnalyzer.js","../action.js","../insights/index.js","../strife.js"],"sourcesContent":["const CMD = {\n // HSHK: 1,\n // EU: 2,\n // SYNC: 4,\n // CONNECT: 8,\n\n CONNECT: 1,\n HSHK: 2,\n EU: 4,\n SYNC: 8,\n};\n\nexport default CMD;\n","import CMD from './cmd.js';\n\nconst CHANNEL_NAME = 'app.broadcast';\n\nexport default class SubscribableChannel extends MessageChannel {\n static _instanceCache;\n #instanceId = crypto.randomUUID(); // Unique ID per iframe\n #subscribers = []; // Track all subscriber handlers\n #broadcastChannel;\n #handleMessage = null;\n #handleBroadcastMessage = null;\n // Frame-coalesced delivery for parent-port messages: drop older queued events\n // and only run the subscriber loop once per animation frame with the latest\n // event. Without this, a multi-subscriber Svelte site (each component doing\n // `page = data`) saturates the iframe main thread under continuous parent\n // broadcasts (typing/drag), and the preview falls progressively behind.\n #pendingMessageEvent = null;\n #flushRaf = null;\n\n static get instance() {\n if (!this._instanceCache) {\n this._instanceCache = new SubscribableChannel();\n }\n\n return this._instanceCache;\n }\n\n constructor() {\n super(); // Initialize MessageChannel (port1, port2)\n\n // Check for stale instances (HMR/cache issue detection)\n if (window.__strifeInstances) {\n window.__strifeInstances++;\n console.warn(`[${window.name}] ⚠️ MULTIPLE SubscribableChannel instances detected (${window.__strifeInstances})!`);\n console.warn(`[${window.name}] 🔄 Please do a HARD REFRESH (Cmd+Shift+R / Ctrl+Shift+R) to clear cached SDK code`);\n } else {\n window.__strifeInstances = 1;\n }\n\n // BroadcastChannel for iframe-to-iframe communication (same origin)\n this.#broadcastChannel = new BroadcastChannel(CHANNEL_NAME);\n }\n\n /**\n * Initialize the channel - send HSHK to parent with port2\n */\n invoke() {\n // Listen for CONNECT acknowledgment from parent on port1\n const handleConnect = (event) => {\n if (event.data.cmd === CMD.CONNECT) {\n this.onConnected(event);\n }\n };\n this.port1.addEventListener('message', handleConnect, {\n once: true,\n });\n this.port1.start();\n\n this._ready = new Promise((resolve, reject) => {\n this.readyResolve = resolve;\n this.readyReject = reject;\n });\n\n // Wait for document ready, then send HSHK to parent\n this._ready.then(() => {\n try {\n window.top.postMessage(\n {\n cmd: CMD.HSHK,\n context: {\n name: window.name,\n height: document.body.scrollHeight,\n path: window.location.pathname\n }\n },\n '*', // targetOrigin (parent's origin)\n [this.port2] // Transfer port2 to parent\n );\n } catch (error) {\n console.error(`[${window.name}] ❌ Failed to send HSHK:`, error);\n this.readyReject(error);\n }\n });\n\n switch (document.readyState) {\n case 'loading':\n case 'interactive': {\n document.onreadystatechange = () => {\n if (document.readyState === 'complete') {\n this.readyResolve();\n }\n };\n break;\n }\n case 'complete':\n this.readyResolve();\n break;\n }\n }\n\n /**\n * Subscribe to messages from parent or other iframes\n * @param {Function} messageHandler - Called when a message is received\n * @returns {Function} Unsubscribe function\n */\n subscribe(messageHandler) {\n if (typeof messageHandler !== 'function') {\n throw new Error('messageHandler must be a function!');\n }\n\n // Add this handler to the subscribers list\n this.#subscribers.push(messageHandler);\n\n // Set up listeners ONLY ONCE on first subscription\n if (this.#handleMessage === null) {\n // Handler for messages from parent via MessageChannel port1.\n // Coalesces to one subscriber-loop per animation frame so a 60 Hz parent\n // broadcast (drag/typing) doesn't queue up an unbounded backlog of\n // Svelte-cascade work in the iframe. Always delivers the LATEST event.\n this.#handleMessage = (event) => {\n this.#pendingMessageEvent = event;\n if (this.#flushRaf !== null) return;\n this.#flushRaf = requestAnimationFrame(() => {\n this.#flushRaf = null;\n const ev = this.#pendingMessageEvent;\n this.#pendingMessageEvent = null;\n if (!ev) return;\n for (const subscriber of this.#subscribers) {\n try {\n subscriber(ev);\n } catch (error) {\n console.error(`[${window.name}] Error in subscriber:`, error);\n }\n }\n });\n };\n\n // Forward messages from parent to sibling iframes via BroadcastChannel\n this.#handleBroadcastMessage = (event) => {\n try {\n // Tag with instance ID before broadcasting\n this.#broadcastChannel.postMessage({\n ...event.data,\n _sourceInstanceId: this.#instanceId,\n _sourceType: 'iframe',\n _sourceName: window.name\n });\n } catch (error) {\n console.error(`[${window.name}] Error in handleBroadcastMessage:`, error);\n }\n };\n\n // Handler for messages from sibling iframes via BroadcastChannel\n const handleBroadcastReceived = (event) => {\n try {\n const isSelf = event.data._sourceInstanceId === this.#instanceId;\n\n // Skip messages from self\n if (isSelf) {\n return;\n }\n\n // Prepare clean data (remove metadata)\n const { _sourceInstanceId, _sourceType, _sourceName, ...data } = event.data;\n\n // Filter sync updates by current path if applicable\n if (data.sync && Array.isArray(data.sync)) {\n const filteredSync = data.sync.filter(update => {\n // If update specifies a path, only process if it matches our current path\n if (update.currentPath) {\n return update.currentPath === window.location.pathname;\n }\n // No path specified, process it\n return true;\n });\n\n // If no updates match our path, skip this message entirely\n if (filteredSync.length === 0) {\n return;\n }\n\n // Replace sync array with filtered version\n data.sync = filteredSync;\n }\n\n const cleanEvent = { ...event, data };\n\n // Call ALL subscribers with the filtered data\n for (const subscriber of this.#subscribers) {\n try {\n subscriber(cleanEvent);\n } catch (error) {\n console.error(`[${window.name}] Error in subscriber:`, error);\n }\n }\n } catch (error) {\n console.error(`[${window.name}] Error in handleBroadcastReceived:`, error);\n }\n };\n\n // Add listeners ONCE\n this.#broadcastChannel.addEventListener('message', handleBroadcastReceived);\n this.port1.addEventListener('message', this.#handleMessage);\n\n // INTENTIONALLY DISABLED: This line caused 3× message amplification (67% excess handler calls)\n //\n // Architecture Decision:\n // Parent messages are now sent directly to ALL iframes via their individual MessageChannel\n // ports (see MessageService.postMessage). BroadcastChannel is ONLY for iframe-to-iframe\n // communication (e.g., height updates), not for forwarding parent messages.\n //\n // The Problem (when enabled):\n // 1. Parent sends SYNC to Desktop iframe via MessageChannel\n // 2. Desktop's handleBroadcastMessage forwards to BroadcastChannel\n // 3. Desktop receives its OWN broadcast (in addition to the direct message)\n // 4. Result: Each iframe processes parent messages 3× (1 direct + 2 sibling broadcasts)\n //\n // DO NOT re-enable without solving the amplification issue.\n //\n // this.port1.addEventListener('message', this.#handleBroadcastMessage);\n }\n\n // Return unsubscribe function\n return () => {\n const index = this.#subscribers.indexOf(messageHandler);\n if (index > -1) {\n this.#subscribers.splice(index, 1);\n }\n };\n }\n\n /**\n * Send a message to parent and siblings\n * @param {Object} payload - Message to send\n */\n send(payload) {\n // Send to parent via MessageChannel port1\n this.port1.postMessage(payload);\n\n // Also broadcast to siblings via BroadcastChannel (tagged with instanceId)\n this.#broadcastChannel.postMessage({\n ...payload,\n _sourceInstanceId: this.#instanceId,\n _sourceType: 'iframe',\n _sourceName: window.name\n });\n }\n\n onConnected(event) {\n return event;\n }\n}\n","export const propertyStringToValue = (propertyString, model) => {\n return propertyString?.split('.').reduce((a, b) => a?.[b], model);\n};","export const TITLE_SEPARATORS = ['|', '-', '–', '—', ':'];\nexport const BRAND_POSITION_END = 'end';\n\nexport const SEO_RULES = {\n TITLE_LENGTH: {\n MIN: 50,\n MAX: 60\n },\n META_DESCRIPTION_LENGTH: {\n MIN: 120,\n MAX: 155\n }\n};\n\nexport const INSIGHTS_IMPACT = {\n ERROR: 'error',\n WARN: 'warn',\n SUCCESS: 'success',\n INFO: 'info'\n};\n\nexport const INSIGHTS_METRICS = {\n SEO: {\n TITLE: {\n MISSING: 'titleMissing',\n LENGTH: 'titleLength',\n SEPARATORS: 'titleSeparators',\n SEGMENTS: 'titleSegments',\n },\n META_DESCRIPTION: {\n MISSING: 'metaDescriptionMissing',\n LENGTH: 'metaDescriptionLength',\n },\n KEYWORDS: {\n COUNT: 'keywordCount',\n DENSITY: 'keywordDensity',\n TITLE: 'keywordTitle',\n META_DESCRIPTION: 'keywordMetaDescription',\n URL: 'keywordUrl',\n HEADINGS: 'keywordHeadings',\n FIRST_PARAGRAPH: 'keyword1stParagraph',\n DISTINCT: 'keywordDistinct',\n },\n },\n CONTENT: {\n PARAGRAPH_TOO_LONG: 'contentParagraphTooLong',\n SENTENCE_TOO_LONG: 'contentSentenceTooLong',\n LIX: 'contentLix',\n FLESCH_EASE: 'contentFleschEase',\n FLESCH_KINCAID: 'contentFleschKincaid',\n GUNNING_FOG: 'contentGunningFog',\n COLEMAN_LIAU: 'contentColemanLiau',\n LONG_WORDS: 'contentLongWords',\n COMPLEX_WORDS: 'contentComplexWords',\n AVERAGE_WORDS_PER_SENTENCE: 'contentAverageWordsPerSentence',\n },\n}\n\n\n// TITLE_MISSING: 'titleMissing',\n// TITLE_LENGTH: 'titleLength',\n// TITLE_SEPARATORS: 'titleSeparators',\n// TITLE_SEGMENTS: 'titleSegments',\n// META_DESCRIPTION_MISSING: 'metaDescriptionMissing',\n// META_DESCRIPTION_LENGTH: 'metaDescriptionLength',\n// KEYWORD_COUNT: 'keywordCount',\n// KEYWORD_DENSITY: 'keywordDensity',\n// KEYWORD_TITLE: 'keywordTitle',\n// KEYWORD_META_DESCRIPTION: 'keywordMetaDescription',\n// KEYWORD_URL: 'keywordUrl',\n// KEYWORD_HEADINGS: 'keywordHeadings',\n// KEYWORD_1ST_PARAGRAPH: 'keyword1stParagraph',\n// KEYWORD_DISTINCT: 'keywordDistinct',\n// CONTENT_PARAGRAPH_TOO_LONG: 'contentParagraphTooLong',\n// CONTENT_SENTENCE_TOO_LONG: 'contentSentenceTooLong',\n// CONTENT_LIX: 'contentLix',\n// CONTENT_FLESCH_EASE: 'contentFleschEase',\n// CONTENT_FLESCH_KINCAID: 'contentFleschKincaid',\n// CONTENT_GUNNING_FOG: 'contentGunningFog',\n// CONTENT_COLEMAN_LIAU: 'contentColemanLiau',\n// CONTENT_LONG_WORDS: 'contentLongWords',\n// CONTENT_COMPLEX_WORDS: 'contentComplexWords',\n// CONTENT_AVERAGE_WORDS_PER_SENTENCE: 'contentAverageWordsPerSentence',","import { INSIGHTS_METRICS } from '../constants.js';\nimport { analyzeTitleFormat } from './titleAnalyzer.js';\n\nexport function analyzeTitle(title) {\n const results = {};\n\n results[INSIGHTS_METRICS.SEO.TITLE.MISSING] = { value: title.length === 0 };\n results[INSIGHTS_METRICS.SEO.TITLE.LENGTH] = { value: title.length };\n\n // Format analysis\n const titleAnalysis = analyzeTitleFormat(title);\n\n results[INSIGHTS_METRICS.SEO.TITLE.SEPARATORS] = { value: titleAnalysis.hasSeparator };\n results[INSIGHTS_METRICS.SEO.TITLE.SEGMENTS] = { value: titleAnalysis.segments.length };\n\n return results;\n}\n\nexport function analyzeMetaDescription(metaDescription) {\n const results = {};\n\n results[INSIGHTS_METRICS.SEO.META_DESCRIPTION.MISSING] = { value: metaDescription.length === 0 };\n results[INSIGHTS_METRICS.SEO.META_DESCRIPTION.LENGTH] = { value: metaDescription.length };\n\n return results;\n}","import { TITLE_SEPARATORS } from '../constants.js';\n\nexport function analyzeTitleFormat(title) {\n const usedSeparator = TITLE_SEPARATORS.find(sep => title.includes(sep));\n\n if (!usedSeparator) {\n return {\n hasSeparator: false,\n segments: [title],\n separator: null\n };\n }\n\n const segments = title.split(usedSeparator).map(s => s.trim());\n return {\n hasSeparator: true,\n segments,\n separator: usedSeparator\n };\n}","import { INSIGHTS_METRICS } from '../constants.js';\n\nfunction escapeRegExp(string) {\n return string.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nfunction normalizeText(text) {\n return text\n .toLowerCase()\n .replace(/[.,/#!$%^&*;:{}=\\-_`~()]/g, '') // Remove punctuation\n .replace(/\\s+/g, ' ') // Normalize whitespace\n .trim();\n}\n\nfunction findKeywordOccurrences(text, keyword) {\n const normalizedText = normalizeText(text);\n const normalizedKeyword = normalizeText(keyword);\n const words = normalizedText.split(' ');\n const keywordWords = normalizedKeyword.split(' ');\n const occurrences = [];\n\n if (keywordWords.length === 1) {\n const regex = new RegExp(`\\\\b${escapeRegExp(normalizedKeyword)}\\\\b`, 'gi');\n const matches = text.match(regex);\n return matches || [];\n }\n\n for (let i = 0; i <= words.length - keywordWords.length; i++) {\n const possibleMatch = words.slice(i, i + keywordWords.length).join(' ');\n if (possibleMatch === normalizedKeyword) {\n const originalTextMatch = text\n .split(/\\s+/)\n .slice(i, i + keywordWords.length)\n .join(' ');\n occurrences.push(originalTextMatch);\n }\n }\n\n return occurrences;\n}\n\nfunction countKeywordInText(text, keyword) {\n return findKeywordOccurrences(text, keyword).length;\n}\n\nexport function analyzeKeywordUsage(document, keywordsInput) {\n let results = {};\n\n if (!keywordsInput.trim()) {\n return results;\n }\n\n const keywords = keywordsInput\n .split(',')\n .map((k) => k.trim())\n .filter((k) => k.length > 0);\n\n keywords.forEach((keyword, index) => {\n const analysis = analyzeKeyword(document, keyword);\n displayResults(results, analysis, keyword);\n });\n\n if (keywords.length > 1) {\n analyzeKeywordRelationships(results, keywords);\n }\n\n return results;\n}\n\nfunction analyzeKeyword(document, keyword) {\n const bodyText = document.body.textContent || '';\n const wordCount = normalizeText(bodyText).split(/\\s+/).length;\n const occurrences = findKeywordOccurrences(bodyText, keyword);\n const keywordCount = occurrences.length;\n const keywordWordCount = keyword.split(/\\s+/).length;\n const density = ((keywordCount * keywordWordCount) / wordCount) * 100;\n\n const title = document.querySelector('title')?.textContent || '';\n const inTitle = findKeywordOccurrences(title, keyword).length > 0;\n\n const firstParagraph = document.querySelector('p')?.textContent || '';\n const inFirstParagraph = findKeywordOccurrences(firstParagraph, keyword).length > 0;\n\n const h1Count = Array.from(document.querySelectorAll('h1')).reduce(\n (count, el) => count + findKeywordOccurrences(el.textContent || '', keyword).length,\n 0,\n );\n const h2Count = Array.from(document.querySelectorAll('h2')).reduce(\n (count, el) => count + findKeywordOccurrences(el.textContent || '', keyword).length,\n 0,\n );\n const h3Count = Array.from(document.querySelectorAll('h3')).reduce(\n (count, el) => count + findKeywordOccurrences(el.textContent || '', keyword).length,\n 0,\n );\n\n const metaDescription = document.querySelector('meta[name=\"description\"]')?.getAttribute('content') || '';\n const inMetaDescription = findKeywordOccurrences(metaDescription, keyword).length > 0;\n\n const url = document.location?.pathname || '';\n const urlKeyword = normalizeText(keyword).replace(/\\s+/g, '-');\n const inUrl = normalizeText(url).includes(urlKeyword);\n\n return {\n density,\n count: keywordCount,\n inTitle,\n inFirstParagraph,\n inHeadings: { h1: h1Count, h2: h2Count, h3: h3Count },\n inMetaDescription,\n inUrl,\n occurrences,\n };\n}\n\nfunction displayResults(results, analysis, keyword) {\n if (!results[INSIGHTS_METRICS.SEO.KEYWORDS.COUNT]) {\n results[INSIGHTS_METRICS.SEO.KEYWORDS.COUNT] = [];\n }\n results[INSIGHTS_METRICS.SEO.KEYWORDS.COUNT].push({ value: analysis.count, additional: { keyword } });\n\n if (!results[INSIGHTS_METRICS.SEO.KEYWORDS.DENSITY]) {\n results[INSIGHTS_METRICS.SEO.KEYWORDS.DENSITY] = [];\n }\n results[INSIGHTS_METRICS.SEO.KEYWORDS.DENSITY].push({ value: analysis.density, additional: { keyword } });\n\n if (!results[INSIGHTS_METRICS.SEO.KEYWORDS.TITLE]) {\n results[INSIGHTS_METRICS.SEO.KEYWORDS.TITLE] = [];\n }\n results[INSIGHTS_METRICS.SEO.KEYWORDS.TITLE].push({ value: analysis.inTitle, additional: { keyword } });\n\n if (!results[INSIGHTS_METRICS.SEO.KEYWORDS.HEADINGS]) {\n results[INSIGHTS_METRICS.SEO.KEYWORDS.HEADINGS] = [];\n }\n results[INSIGHTS_METRICS.SEO.KEYWORDS.HEADINGS].push({\n value: analysis.inHeadings.h1 + analysis.inHeadings.h2 + analysis.inHeadings.h3,\n additional: { keyword },\n });\n\n if (!results[INSIGHTS_METRICS.SEO.KEYWORDS.FIRST_PARAGRAPH]) {\n results[INSIGHTS_METRICS.SEO.KEYWORDS.FIRST_PARAGRAPH] = [];\n }\n results[INSIGHTS_METRICS.SEO.KEYWORDS.FIRST_PARAGRAPH].push({ value: analysis.inFirstParagraph, additional: { keyword } });\n\n if (!results[INSIGHTS_METRICS.SEO.KEYWORDS.META_DESCRIPTION]) {\n results[INSIGHTS_METRICS.SEO.KEYWORDS.META_DESCRIPTION] = [];\n }\n results[INSIGHTS_METRICS.SEO.KEYWORDS.META_DESCRIPTION].push({\n value: analysis.inMetaDescription,\n additional: { keyword },\n });\n\n if (!results[INSIGHTS_METRICS.SEO.KEYWORDS.URL]) {\n results[INSIGHTS_METRICS.SEO.KEYWORDS.URL] = [];\n }\n results[INSIGHTS_METRICS.SEO.KEYWORDS.URL].push({ value: analysis.inUrl, additional: { keyword } });\n}\n\nfunction analyzeKeywordRelationships(results, keywords) {\n if (!results[INSIGHTS_METRICS.SEO.KEYWORDS.DISTINCT]) {\n results[INSIGHTS_METRICS.SEO.KEYWORDS.DISTINCT] = [];\n }\n const similarities = [];\n\n for (let i = 0; i < keywords.length; i++) {\n for (let j = i + 1; j < keywords.length; j++) {\n const similarity = calculateSimilarity(keywords[i], keywords[j]);\n if (similarity > 0.3) {\n results[INSIGHTS_METRICS.SEO.KEYWORDS.DISTINCT].push({\n value: similarities.length === 0,\n additional: { similarities: [keywords[i], keywords[j], similarity] },\n });\n }\n }\n }\n}\n\nfunction calculateSimilarity(str1, str2) {\n const set1 = new Set(str1.toLowerCase().split(' '));\n const set2 = new Set(str2.toLowerCase().split(' '));\n const intersection = new Set([...set1].filter((x) => set2.has(x)));\n const union = new Set([...set1, ...set2]);\n return intersection.size / union.size;\n}\n","import { INSIGHTS_METRICS } from \"../constants.js\";\n\nfunction calculateMetrics(text, language) {\n const words = text.split(/\\s+/).filter(word => word.length > 0);\n const sentences = text.split(/[.!?]+/).filter(sentence => sentence.trim().length > 0);\n const totalSyllables = countSyllables(text);\n const complexWords = words.filter(word => countWordSyllables(word) > 2).length;\n\n const totalWords = words.length;\n const totalSentences = sentences.length;\n const averageWordsPerSentence = totalWords / totalSentences;\n const averageSyllablesPerWord = totalSyllables / totalWords;\n const chars = text.replace(/\\s/g, '').length;\n const averageCharsPerWord = chars / totalWords;\n\n const lix = calculateLIX(text);\n const longWords = words.filter(word => word.length > 15).length;\n\n return {\n fleschEase: 206.835 - (1.015 * averageWordsPerSentence) - (84.6 * averageSyllablesPerWord),\n fleschKincaid: (0.39 * averageWordsPerSentence) + (11.8 * averageSyllablesPerWord) - 15.59,\n gunningFog: 0.4 * (averageWordsPerSentence + 100 * (complexWords / totalWords)),\n colemanLiau: (0.0588 * (averageCharsPerWord * 100)) - (0.296 * (totalSentences / totalWords * 100)) - 15.8,\n averageWordsPerSentence,\n averageSyllablesPerWord,\n totalWords,\n totalSentences,\n complexWords,\n lix,\n longWords\n };\n}\n\nfunction countSyllables(text) {\n const words = text.toLowerCase().split(/\\s+/);\n return words.reduce((total, word) => {\n return total + countWordSyllables(word);\n }, 0);\n}\n\nfunction countWordSyllables(word) {\n word = word.toLowerCase().replace(/[^a-z]/g, '');\n if (word.length <= 3) return 1;\n\n word = word.replace(/(?:[^laeiouy]es|ed|[^laeiouy]e)$/, '');\n word = word.replace(/^y/, '');\n const syllables = word.match(/[aeiouy]{1,2}/g);\n return syllables ? syllables.length : 1;\n}\n\nfunction calculateLIX(text) {\n const words = text.split(/\\s+/).filter(word => word.length > 0);\n const sentences = text.split(/[.!?]+/).filter(sentence => sentence.trim().length > 0);\n const longWords = words.filter(word => word.length > 6).length;\n\n return (words.length / sentences.length) + (longWords * 100 / words.length);\n}\n\nexport function analyzeContent(document) {\n const results = {};\n\n const language = document.documentElement.lang.toLowerCase().split('-')[0] || 'en';\n\n const paragraphs = document.querySelectorAll('p');\n if (paragraphs.length === 0) {\n return;\n }\n\n // Analyze each paragraph individually\n const tooLongParagraphs = [];\n const tooLongSentences = [];\n for (const [index, paragraph] of Array.from(paragraphs).entries()) {\n const text = paragraph.textContent?.trim() || '';\n if (text.length === 0) continue;\n\n const words = text.split(/\\s+/).filter(word => word.length > 0);\n if (words.length > 40) {\n tooLongParagraphs.push(index + 1);\n }\n\n const sentences = text.split(/[.!?]+/).filter(sentence => sentence.trim().length > 0);\n for (const sentence of sentences) {\n const sentenceWords = sentence.trim().split(/\\s+/).length;\n if (sentenceWords > 20) {\n tooLongSentences.push(index + 1);\n }\n }\n }\n\n if (tooLongParagraphs.length > 0) {\n results[INSIGHTS_METRICS.CONTENT.PARAGRAPH_TOO_LONG] = {value: true, additional: tooLongParagraphs};\n }\n if (tooLongSentences.length > 0) {\n results[INSIGHTS_METRICS.CONTENT.SENTENCE_TOO_LONG] = {value: true, additional: tooLongSentences};\n }\n\n // Analyze overall content\n const fullText = Array.from(paragraphs)\n .map(p => p.textContent?.trim())\n .filter(Boolean)\n .join(' ');\n\n const metrics = calculateMetrics(fullText, language);\n\n if (language === 'sv') {\n results[INSIGHTS_METRICS.CONTENT.LIX] = {value: metrics.lix};\n } else {\n results[INSIGHTS_METRICS.CONTENT.FLESCH_EASE] = {value: metrics.fleschEase};\n results[INSIGHTS_METRICS.CONTENT.FLESCH_KINCAID] = {value: metrics.fleschKincaid};\n results[INSIGHTS_METRICS.CONTENT.GUNNING_FOG] = {value: metrics.gunningFog};\n results[INSIGHTS_METRICS.CONTENT.COLEMAN_LIAU] = {value: metrics.colemanLiau};\n }\n\n results[INSIGHTS_METRICS.CONTENT.AVERAGE_WORDS_PER_SENTENCE] = {value: metrics.averageWordsPerSentence, additional: metrics.totalSentences};\n\n if (language === 'sv') {\n results[INSIGHTS_METRICS.CONTENT.LONG_WORDS] = {value: metrics.longWords, additional: metrics.totalWords};\n } else {\n results[INSIGHTS_METRICS.CONTENT.COMPLEX_WORDS] = {value: metrics.complexWords, additional: metrics.totalWords};\n }\n\n return results;\n}\n","// const ACTION = {\n// NONE: 8,\n// EDIT: 16,\n// RESET: 32,\n// INIT: 64,\n// SYNC: 128,\n// STATE: 256,\n// FOCUS: 512,\n// };\n\nconst PREVIEWACTION = {\n SYNC: 4,\n INIT: 8,\n FOCUS: 16,\n UPDATE: 32,\n INSIGHTS: 64,\n};\n\nexport default PREVIEWACTION;\n","import SubscribableChannel from '../subscribableChannel.js';\nimport * as analyzers from './analyzers/index.js';\nimport CMD from '../cmd.js';\nimport PREVIEWACTION from '../action.js';\n\nlet insightsTimeout;\n\nconst sendInsights = (context) => {\n const model = context.draft ?? context.model;\n const title = document.querySelector('title')?.textContent ?? '';\n const metaDesc = document.querySelector('meta[name=\"description\"]')?.getAttribute('content') || '';\n const keywords = model?.serp?.keywords ?? '';\n\n const insights = {\n seo: {\n title: analyzers.analyzeTitle(title),\n metaDescription: analyzers.analyzeMetaDescription(metaDesc),\n keywords: analyzers.analyzeKeywordUsage(document, keywords),\n },\n content: analyzers.analyzeContent(document),\n };\n\n const messageChannel = SubscribableChannel.instance;\n messageChannel.send({\n cmd: CMD.EU,\n updates: [\n { action: PREVIEWACTION.INSIGHTS, context: { name: window.name, timeStamp: new Date().toJSON(), insights } },\n ],\n });\n};\n\nexport const runInsights = (context) => {\n if (!context?.bucket?.insightsEnabled) {\n return;\n }\n clearTimeout(insightsTimeout);\n insightsTimeout = setTimeout(() => sendInsights(context), 1000);\n};\n","import SubscribableChannel from './subscribableChannel.js';\nimport { propertyStringToValue } from '../../functions/propertyStringToValue.js';\nimport { runInsights } from './insights/index.js';\nimport CMD from './cmd.js';\nimport PREVIEWACTION from './action.js';\n\nlet stateInitialized = false;\nlet state = {};\nlet context = {};\nlet placeholders = [];\n\nconst handlers = [];\n\nconst defaultHandler = ({ data }) => {\n try {\n if (data.cmd === CMD.SYNC) {\n data.sync.forEach((update) => {\n if (update.currentPath !== window.location.pathname) {\n return;\n }\n\n switch (update.action) {\n case PREVIEWACTION.INIT:\n handlers.forEach(({ self, handler }) => {\n // Init placeholders\n const currentUpdate = (update.data.placeholders ?? []).find((d) => d.propertyName === self.dataset.field);\n if (currentUpdate) {\n self.dataset.placeholder = currentUpdate.placeholder;\n }\n });\n placeholders = [...(update.data?.placeholder ?? [])];\n if (update.context) {\n context = { ...update.context };\n }\n runInsights(context);\n break;\n case PREVIEWACTION.UPDATE:\n const change = update.data?.change;\n if (change) {\n //If change is provided, only update the field that changed\n handlers.forEach(({ self, handler }) => {\n if (change.name === self.dataset.field) {\n handler(change.value, update.context);\n }\n });\n } else if (update.data?.state) {\n //If only state is provided, update all fields\n handlers.forEach(({ self, handler }) => {\n const value = propertyStringToValue(self.dataset.field, update.data.state);\n if (value !== undefined) {\n handler(value, update.context);\n }\n });\n }\n\n if (update.data?.state) {\n state = { ...update.data.state };\n stateInitialized = true;\n }\n if (update.context) {\n context = { ...update.context };\n }\n runInsights(context);\n break;\n case PREVIEWACTION.FOCUS:\n break;\n }\n });\n }\n } catch (error) {\n console.error(error);\n }\n};\n\nconst useState = (self, handler) => {\n const entry = { self, handler };\n handlers.push(entry);\n\n //If state is already initialized, call handler with current state to initialize with current state\n if (stateInitialized) {\n const value = propertyStringToValue(self.dataset.field, state);\n if (value !== undefined) {\n handler(value, context);\n }\n }\n if (placeholders.length) {\n const placeholderValue = placeholders.find((d) => d.propertyName === self.dataset.field);\n if (placeholderValue) {\n self.dataset.placeholder = placeholderValue.placeholder || '';\n }\n }\n\n // Return cleanup function for disconnectedCallback\n return () => {\n const idx = handlers.indexOf(entry);\n if (idx > -1) handlers.splice(idx, 1);\n };\n};\n\nconst subscribe = (messageHandler) => {\n if (typeof messageHandler !== 'function') {\n throw new Error('messageHandler must be a function!');\n }\n\n const handleMessage = (event) => {\n try {\n // Filter out sync messages containing state updates\n if (event.data.cmd === CMD.SYNC) {\n for (const update of event.data.sync) {\n if (update.action === PREVIEWACTION.UPDATE) {\n messageHandler(update.data.state);\n continue;\n }\n }\n }\n } catch (error) {\n console.error('Error in messageHandler:', error);\n }\n };\n\n //If state is already initialized, call handler with current state to initialize with current state\n if (stateInitialized) {\n messageHandler(state);\n }\n\n return SubscribableChannel.instance.subscribe(handleMessage);\n};\n\nconst initResizeObserver = () => {\n const debounce = (func, wait) => {\n let timeout;\n return function (...args) {\n clearTimeout(timeout);\n timeout = setTimeout(() => func.apply(this, args), wait);\n };\n };\n const sendHeightUpdate = () => {\n const messageChannel = SubscribableChannel.instance;\n messageChannel.send({\n cmd: CMD.EU,\n updates: [{ action: PREVIEWACTION.SYNC, context: { name: window.name, height: document.body.scrollHeight } }],\n });\n };\n const debouncedSendHeightUpdate = debounce(sendHeightUpdate, 100);\n\n const resizeObserver = new ResizeObserver((entries) => {\n for (let entry of entries) {\n if (entry.target === document.body) {\n debouncedSendHeightUpdate();\n }\n }\n });\n\n resizeObserver.observe(document.body);\n};\n\nif (typeof document !== 'undefined') {\n document.addEventListener('DOMContentLoaded', (evt) => {\n import('./composition/index.js');\n\n SubscribableChannel.instance.invoke();\n\n SubscribableChannel.instance.subscribe(defaultHandler);\n\n //Add resize observer on document.body to send height to messageChannel\n initResizeObserver();\n });\n}\n\nexport { useState, subscribe };\n"],"names":["CMD","SubscribableChannel","MessageChannel","static","instanceId","crypto","randomUUID","subscribers","broadcastChannel","handleMessage","handleBroadcastMessage","pendingMessageEvent","flushRaf","instance","this","_instanceCache","constructor","super","window","__strifeInstances","console","warn","name","BroadcastChannel","invoke","port1","addEventListener","event","data","cmd","onConnected","once","start","_ready","Promise","resolve","reject","readyResolve","readyReject","then","top","postMessage","context","height","document","body","scrollHeight","path","location","pathname","port2","error","readyState","onreadystatechange","subscribe","messageHandler","Error","push","requestAnimationFrame","ev","subscriber","_sourceInstanceId","_sourceType","_sourceName","handleBroadcastReceived","sync","Array","isArray","filteredSync","filter","update","currentPath","length","cleanEvent","index","indexOf","splice","send","payload","propertyStringToValue","propertyString","model","split","reduce","a","b","TITLE_SEPARATORS","INSIGHTS_METRICS","SEO","TITLE","MISSING","LENGTH","SEPARATORS","SEGMENTS","META_DESCRIPTION","KEYWORDS","COUNT","DENSITY","URL","HEADINGS","FIRST_PARAGRAPH","DISTINCT","CONTENT","PARAGRAPH_TOO_LONG","SENTENCE_TOO_LONG","LIX","FLESCH_EASE","FLESCH_KINCAID","GUNNING_FOG","COLEMAN_LIAU","LONG_WORDS","COMPLEX_WORDS","AVERAGE_WORDS_PER_SENTENCE","analyzeTitle","title","results","value","titleAnalysis","usedSeparator","find","sep","includes","hasSeparator","segments","map","s","trim","separator","analyzeTitleFormat","analyzeMetaDescription","metaDescription","normalizeText","text","toLowerCase","replace","findKeywordOccurrences","keyword","normalizedText","normalizedKeyword","words","keywordWords","occurrences","regex","RegExp","string","match","i","slice","join","originalTextMatch","analyzeKeywordUsage","keywordsInput","keywords","k","forEach","analysis","bodyText","textContent","wordCount","keywordCount","keywordWordCount","density","querySelector","inTitle","firstParagraph","inFirstParagraph","h1Count","from","querySelectorAll","count","el","h2Count","h3Count","getAttribute","inMetaDescription","url","urlKeyword","inUrl","inHeadings","h1","h2","h3","analyzeKeyword","additional","displayResults","similarities","j","similarity","calculateSimilarity","analyzeKeywordRelationships","str1","str2","set1","Set","set2","intersection","x","has","union","size","calculateMetrics","language","word","sentences","sentence","totalSyllables","total","countWordSyllables","countSyllables","complexWords","totalWords","totalSentences","averageWordsPerSentence","averageSyllablesPerWord","averageCharsPerWord","lix","longWords","calculateLIX","fleschEase","fleschKincaid","gunningFog","colemanLiau","syllables","analyzeContent","documentElement","lang","paragraphs","tooLongParagraphs","tooLongSentences","paragraph","entries","metrics","p","Boolean","PREVIEWACTION","insightsTimeout","runInsights","bucket","insightsEnabled","clearTimeout","setTimeout","draft","metaDesc","serp","insights","seo","analyzers.analyzeTitle","analyzers.analyzeMetaDescription","analyzers.analyzeKeywordUsage","content","analyzers.analyzeContent","updates","action","timeStamp","Date","toJSON","sendInsights","stateInitialized","state","placeholders","handlers","defaultHandler","self","handler","currentUpdate","d","propertyName","dataset","field","placeholder","change","undefined","useState","entry","placeholderValue","idx","initResizeObserver","debouncedSendHeightUpdate","func","wait","timeout","args","apply","debounce","ResizeObserver","target","observe","evt","import"],"mappings":"AAAA,MAAMA,EAMK,EANLA,EAOE,EAPFA,EAQA,EARAA,EASE,ECLO,MAAMC,UAA4BC,eAC/CC,sBACAC,GAAcC,OAAOC,aACrBC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,CAAEpB,KAAMJ,OAAOI,KAAMqB,OAAQC,SAASC,KAAKC,iBAC5F,GAEyD,KAEtC,IAAI8O,gBAAgBtD,IACzC,IAAK,IAAI2C,KAAS3C,EACZ2C,EAAMY,SAAWjP,SAASC,MAC5BwO,GAEJ,IAGaS,QAAQlP,SAASC,KAAK,EAGf,oBAAbD,UACTA,SAASlB,iBAAiB,oBAAqBqQ,IAC7CC,OAAO,uBAEP/R,EAAoBY,SAASW,SAE7BvB,EAAoBY,SAASyC,UAAU+M,GAGvCe,GAAoB"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{u as e,p as t}from'./index-Cng38i9R.js';class n extends HTMLAnchorElement{constructor(){super(),this.tabIndex=0}connectedCallback(){this._cleanup=e(this,(e=>this.render(e)))}disconnectedCallback(){this._cleanup?.()}render(e){if(e){this.href=e.href;const t=this.childNodes;if(0===t.length)this.textContent=e.text;else for(const n of t)n.nodeType===Node.TEXT_NODE&&(n.nodeValue=e.text);'_blank'===e.target&&(this.target=e.target)}}}customElements.define('str-anchor',n,{extends:'a'});class s extends HTMLPictureElement{constructor(){super(),this.sources=[...this.querySelectorAll('source')],this.image=this.querySelector('img')}connectedCallback(){this._cleanup=e(this,(e=>this.render(e)))}disconnectedCallback(){this._cleanup?.()}render(e){let t=!1;this.sources.forEach((n=>{n.srcset=e?.[n.dataset?.propertyMedia]?.source?.url||'',n.srcset&&(t=!0)})),t?(this.image.src=this.image.currentSrc,this.image.classList.remove('str-empty')):(this.image.src='',this.image.classList.add('str-empty'))}}customElements.define('str-picture',s,{extends:'picture'});class c extends HTMLImageElement{constructor(){super()}connectedCallback(){this._cleanup=e(this,(e=>this.render(e)))}disconnectedCallback(){this._cleanup?.()}render(e){this.src=e?.source?.url||'',this.src?this.classList.remove('str-empty'):this.classList.add('str-empty')}}customElements.define('str-img',c,{extends:'img'});class a extends HTMLTimeElement{constructor(){super(),this.tabIndex=0}connectedCallback(){this._cleanup=e(this,(e=>this.render(e)))}disconnectedCallback(){this._cleanup?.()}render(e){e&&(this.textContent=((e,t)=>{if(!t)return e;const n=new Date(e);if(isNaN(n))return'Invalid Date';const s=n.getFullYear(),c=String(s).slice(-2),a=String(n.getMonth()+1).padStart(2,'0'),l=new Intl.DateTimeFormat('en-US',{month:'short'}).format(n),d={yyyy:s,yy:c,MMMM:new Intl.DateTimeFormat('en-US',{month:'long'}).format(n),MMM:l,MM:a,dd:String(n.getDate()).padStart(2,'0'),d:String(n.getDate()),hh:String(n.getHours()).padStart(2,'0'),mm:String(n.getMinutes()).padStart(2,'0'),ss:String(n.getSeconds()).padStart(2,'0')},i=new RegExp(Object.keys(d).join('|'),'g');return t.replace(i,(e=>d[e]))})(e,this.dataset.format))}}customElements.define('str-time',a,{extends:'time'});const l=t=>e(t,(e=>{d(t,e)})),d=(e,t)=>{e.textContent=t};customElements.define('str-address',class extends HTMLElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'address'}),customElements.define('str-p',class extends HTMLParagraphElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'p'}),customElements.define('str-span',class extends HTMLSpanElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'span'}),customElements.define('str-strong',class extends HTMLElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'strong'}),customElements.define('str-h1',class extends HTMLHeadingElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'h1'}),customElements.define('str-h2',class extends HTMLHeadingElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'h2'}),customElements.define('str-h3',class extends HTMLHeadingElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'h3'}),customElements.define('str-h4',class extends HTMLHeadingElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'h4'}),customElements.define('str-h5',class extends HTMLHeadingElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'h5'}),customElements.define('str-h6',class extends HTMLHeadingElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'h6'}),customElements.define('str-abbr',class extends HTMLElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'abbr'}),customElements.define('str-b',class extends HTMLElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'b'}),customElements.define('str-button',class extends HTMLButtonElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'button'}),customElements.define('str-cite',class extends HTMLElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'cite'}),customElements.define('str-code',class extends HTMLElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'code'}),customElements.define('str-dfn',class extends HTMLElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'dfn'}),customElements.define('str-em',class extends HTMLElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'em'}),customElements.define('str-i',class extends HTMLElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'i'}),customElements.define('str-label',class extends HTMLLabelElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'label'}),customElements.define('str-mark',class extends HTMLElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'mark'}),customElements.define('str-q',class extends HTMLQuoteElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'q'}),customElements.define('str-sub',class extends HTMLElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'sub'}),customElements.define('str-sup',class extends HTMLElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'sup'}),customElements.define('str-td',class extends HTMLTableCellElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'td'});const i=t=>e(t,((e,n)=>{r(t,e,n)})),r=(e,t,n)=>{o(e,t,n)},o=(e,n,s)=>{let c=e.dataset.type||null;switch(c||(c=((e,t)=>{const n=t?.templates?.find((e=>e.collection===t.model?.['@metadata']?.['@collection']));let s=e;e?.includes('.')&&(s=e.split('.')[0]);const c=n?.editors?.find((e=>e.editor.propertyName===s)),a=c?.editor.type;if(e!==s)switch(a){case'chapters':const[n,a]=e.split('.').slice(1);if(!t.draft)return void console.warn('No draft value found in context ',t);const l=t.draft[s]?.[Number(n)];if(!l)return;const d=t.templates.find((e=>e.normalizedName===l['@strife']?.template)),i=d?.editors?.find((e=>e.editor.propertyName===a));return i?.editor.type;case'collection':const[r,o]=e.split('.').slice(1),h=t?.templates?.find((e=>e.collection===t.iterate?.['@metadata']?.['@collection'])),m=h?.editors?.find((e=>e.editor.propertyName===o));return m?.editor.type;case'content-template':const[u]=e.split('.').slice(1),p=t?.templates?.find((e=>e.normalizedName?.toLowerCase()===c.editor.attributes?.templateId?.toLowerCase()||e.id?.toLowerCase()===c.editor.attributes?.templateId?.toLowerCase())),b=p?.editors?.find((e=>e.editor.propertyName===u));return b?.editor.type}return a})(e.dataset.field,s)),e.innerHTML='',c){case'collection':((e,n,s)=>{n.documents&&n.documents.forEach(((n,c)=>{const a=e.dataset.field.lastIndexOf('.'),l=e.dataset.field.substring(a+1);let d=document.getElementById(`collection_${l}`).content;e.appendChild(d.cloneNode(!0)),e.querySelectorAll(`[is^="str-"]:not([data-field^="${e.dataset.field}."])`).forEach((a=>{const l=a.dataset.field;a.dataset.field=`${e.dataset.field}.${c}.${l}`,'function'==typeof a.render?a.render(t(l,n),{...s,iterate:n}):console.warn(`Field ${a.dataset.field} (${a.tagName}) does not have a render method.`)}))}))})(e,n,s);break;case'chapters':((e,n,s)=>{n&&n.forEach(((n,c)=>{let a=document.getElementById(n['@strife'].template);if(!a)return void console.warn('Template not found for chapter:',n['@strife'].template);let l=a.content.cloneNode(!0);l.querySelectorAll('*').forEach((e=>{[...e.attributes].forEach((s=>{if(s.name.startsWith('data-prop-')){const c=s.name.replace('data-prop-',''),a=t(c,n);a&&e.setAttribute(s.name,a)}}))})),e.appendChild(l),e.querySelectorAll(`[is^="str-"]:not([data-field^="${e.dataset.field}."])`).forEach(((a,l)=>{const d=a.dataset.field;a.dataset.field=`${e.dataset.field}.${c}.${d}`,'function'==typeof a.render?a.render(t(d,n),s):console.warn(`Field ${a.dataset.field} (${a.tagName}) does not have a render method.`)}))}))})(e,n,s);break;case'html':e.innerHTML=n;break;case'text':e.textContent=n;break;case'multi-input':((e,t,n)=>{const s=e.dataset.field.lastIndexOf('.'),c=e.dataset.field.substring(s+1);t&&Array.isArray(t)&&t.forEach((t=>{let n=document.getElementById(`multiinput_${c}`);if(n){let s=n.content.cloneNode(!0);const c=s.querySelector('[data-value]');c&&(c.textContent=t),e.appendChild(s)}}))})(e,n);break;case'assets':((e,t,n)=>{const s=e.dataset.field.lastIndexOf('.'),c=e.dataset.field.substring(s+1);t&&Array.isArray(t)&&t.forEach((t=>{let n=document.getElementById(`assets_${c}`);if(n){let s=n.content.cloneNode(!0);const c=s.querySelector('[data-name]');c&&(c.textContent=t.name);const a=s.querySelector('[data-original]');a&&(a.textContent=t.original);const l=s.querySelector('[data-thumbnail]');l&&(l.textContent=t.thumbnail);const d=s.querySelector('[data-size]');d&&(d.textContent=t.size),e.appendChild(s)}}))})(e,n);break;default:e.innerHTML=`<p>Unsupported container type: ${c} for ${e.tagName} and field ${e.dataset.field}</p>`}};customElements.define('str-div',class extends HTMLDivElement{connectedCallback(){this._cleanup=i(this)}disconnectedCallback(){this._cleanup?.()}render(e,t){r(this,e,t)}},{extends:'div'}),customElements.define('str-ul',class extends HTMLUListElement{connectedCallback(){this._cleanup=i(this)}disconnectedCallback(){this._cleanup?.()}render(e,t){r(this,e,t)}},{extends:'ul'}),customElements.define('str-ol',class extends HTMLOListElement{connectedCallback(){this._cleanup=i(this)}disconnectedCallback(){this._cleanup?.()}render(e,t){r(this,e,t)}},{extends:'ol'}),customElements.define('str-section',class extends HTMLElement{connectedCallback(){this._cleanup=i(this)}disconnectedCallback(){this._cleanup?.()}render(e,t){r(this,e,t)}},{extends:'section'}),customElements.define('str-header',class extends HTMLElement{connectedCallback(){this._cleanup=i(this)}disconnectedCallback(){this._cleanup?.()}render(e,t){r(this,e,t)}},{extends:'header'}),customElements.define('str-footer',class extends HTMLElement{connectedCallback(){this._cleanup=i(this)}disconnectedCallback(){this._cleanup?.()}render(e,t){r(this,e,t)}},{extends:'footer'}),customElements.define('str-nav',class extends HTMLElement{connectedCallback(){this._cleanup=i(this)}disconnectedCallback(){this._cleanup?.()}render(e,t){r(this,e,t)}},{extends:'nav'}),customElements.define('str-article',class extends HTMLElement{connectedCallback(){this._cleanup=i(this)}disconnectedCallback(){this._cleanup?.()}render(e,t){r(this,e,t)}},{extends:'article'}),customElements.define('str-main',class extends HTMLElement{connectedCallback(){this._cleanup=i(this)}disconnectedCallback(){this._cleanup?.()}render(e,t){r(this,e,t)}},{extends:'main'}),customElements.define('str-aside',class extends HTMLElement{connectedCallback(){this._cleanup=i(this)}disconnectedCallback(){this._cleanup?.()}render(e,t){r(this,e,t)}},{extends:'aside'}),customElements.define('str-blockquote',class extends HTMLElement{connectedCallback(){this._cleanup=i(this)}disconnectedCallback(){this._cleanup?.()}render(e,t){r(this,e,t)}},{extends:'blockquote'}),customElements.define('str-tbody',class extends HTMLTableSectionElement{connectedCallback(){this._cleanup=i(this)}disconnectedCallback(){this._cleanup?.()}render(e,t){r(this,e,t)}},{extends:'tbody'});
|
|
2
|
-
//# sourceMappingURL=index-
|
|
1
|
+
import{u as e,p as t}from'./index-BIjDe1U1.js';class n extends HTMLAnchorElement{constructor(){super(),this.tabIndex=0}connectedCallback(){this._cleanup=e(this,(e=>this.render(e)))}disconnectedCallback(){this._cleanup?.()}render(e){if(e){this.href=e.href;const t=this.childNodes;if(0===t.length)this.textContent=e.text;else for(const n of t)n.nodeType===Node.TEXT_NODE&&(n.nodeValue=e.text);'_blank'===e.target&&(this.target=e.target)}}}customElements.define('str-anchor',n,{extends:'a'});class s extends HTMLPictureElement{constructor(){super(),this.sources=[...this.querySelectorAll('source')],this.image=this.querySelector('img')}connectedCallback(){this._cleanup=e(this,(e=>this.render(e)))}disconnectedCallback(){this._cleanup?.()}render(e){let t=!1;this.sources.forEach((n=>{n.srcset=e?.[n.dataset?.propertyMedia]?.source?.url||'',n.srcset&&(t=!0)})),t?(this.image.src=this.image.currentSrc,this.image.classList.remove('str-empty')):(this.image.src='',this.image.classList.add('str-empty'))}}customElements.define('str-picture',s,{extends:'picture'});class c extends HTMLImageElement{constructor(){super()}connectedCallback(){this._cleanup=e(this,(e=>this.render(e)))}disconnectedCallback(){this._cleanup?.()}render(e){this.src=e?.source?.url||'',this.src?this.classList.remove('str-empty'):this.classList.add('str-empty')}}customElements.define('str-img',c,{extends:'img'});class a extends HTMLTimeElement{constructor(){super(),this.tabIndex=0}connectedCallback(){this._cleanup=e(this,(e=>this.render(e)))}disconnectedCallback(){this._cleanup?.()}render(e){e&&(this.textContent=((e,t)=>{if(!t)return e;const n=new Date(e);if(isNaN(n))return'Invalid Date';const s=n.getFullYear(),c=String(s).slice(-2),a=String(n.getMonth()+1).padStart(2,'0'),l=new Intl.DateTimeFormat('en-US',{month:'short'}).format(n),d={yyyy:s,yy:c,MMMM:new Intl.DateTimeFormat('en-US',{month:'long'}).format(n),MMM:l,MM:a,dd:String(n.getDate()).padStart(2,'0'),d:String(n.getDate()),hh:String(n.getHours()).padStart(2,'0'),mm:String(n.getMinutes()).padStart(2,'0'),ss:String(n.getSeconds()).padStart(2,'0')},i=new RegExp(Object.keys(d).join('|'),'g');return t.replace(i,(e=>d[e]))})(e,this.dataset.format))}}customElements.define('str-time',a,{extends:'time'});const l=t=>e(t,(e=>{d(t,e)})),d=(e,t)=>{e.textContent=t};customElements.define('str-address',class extends HTMLElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'address'}),customElements.define('str-p',class extends HTMLParagraphElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'p'}),customElements.define('str-span',class extends HTMLSpanElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'span'}),customElements.define('str-strong',class extends HTMLElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'strong'}),customElements.define('str-h1',class extends HTMLHeadingElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'h1'}),customElements.define('str-h2',class extends HTMLHeadingElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'h2'}),customElements.define('str-h3',class extends HTMLHeadingElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'h3'}),customElements.define('str-h4',class extends HTMLHeadingElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'h4'}),customElements.define('str-h5',class extends HTMLHeadingElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'h5'}),customElements.define('str-h6',class extends HTMLHeadingElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'h6'}),customElements.define('str-abbr',class extends HTMLElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'abbr'}),customElements.define('str-b',class extends HTMLElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'b'}),customElements.define('str-button',class extends HTMLButtonElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'button'}),customElements.define('str-cite',class extends HTMLElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'cite'}),customElements.define('str-code',class extends HTMLElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'code'}),customElements.define('str-dfn',class extends HTMLElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'dfn'}),customElements.define('str-em',class extends HTMLElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'em'}),customElements.define('str-i',class extends HTMLElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'i'}),customElements.define('str-label',class extends HTMLLabelElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'label'}),customElements.define('str-mark',class extends HTMLElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'mark'}),customElements.define('str-q',class extends HTMLQuoteElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'q'}),customElements.define('str-sub',class extends HTMLElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'sub'}),customElements.define('str-sup',class extends HTMLElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'sup'}),customElements.define('str-td',class extends HTMLTableCellElement{connectedCallback(){this._cleanup=l(this)}disconnectedCallback(){this._cleanup?.()}render(e){d(this,e)}},{extends:'td'});const i=t=>e(t,((e,n)=>{r(t,e,n)})),r=(e,t,n)=>{o(e,t,n)},o=(e,n,s)=>{let c=e.dataset.type||null;switch(c||(c=((e,t)=>{const n=t?.templates?.find((e=>e.collection===t.model?.['@metadata']?.['@collection']));let s=e;e?.includes('.')&&(s=e.split('.')[0]);const c=n?.editors?.find((e=>e.editor.propertyName===s)),a=c?.editor.type;if(e!==s)switch(a){case'chapters':const[n,a]=e.split('.').slice(1);if(!t.draft)return void console.warn('No draft value found in context ',t);const l=t.draft[s]?.[Number(n)];if(!l)return;const d=t.templates.find((e=>e.normalizedName===l['@strife']?.template)),i=d?.editors?.find((e=>e.editor.propertyName===a));return i?.editor.type;case'collection':const[r,o]=e.split('.').slice(1),h=t?.templates?.find((e=>e.collection===t.iterate?.['@metadata']?.['@collection'])),m=h?.editors?.find((e=>e.editor.propertyName===o));return m?.editor.type;case'content-template':const[u]=e.split('.').slice(1),p=t?.templates?.find((e=>e.normalizedName?.toLowerCase()===c.editor.attributes?.templateId?.toLowerCase()||e.id?.toLowerCase()===c.editor.attributes?.templateId?.toLowerCase())),b=p?.editors?.find((e=>e.editor.propertyName===u));return b?.editor.type}return a})(e.dataset.field,s)),e.innerHTML='',c){case'collection':((e,n,s)=>{n.documents&&n.documents.forEach(((n,c)=>{const a=e.dataset.field.lastIndexOf('.'),l=e.dataset.field.substring(a+1);let d=document.getElementById(`collection_${l}`).content;e.appendChild(d.cloneNode(!0)),e.querySelectorAll(`[is^="str-"]:not([data-field^="${e.dataset.field}."])`).forEach((a=>{const l=a.dataset.field;a.dataset.field=`${e.dataset.field}.${c}.${l}`,'function'==typeof a.render?a.render(t(l,n),{...s,iterate:n}):console.warn(`Field ${a.dataset.field} (${a.tagName}) does not have a render method.`)}))}))})(e,n,s);break;case'chapters':((e,n,s)=>{n&&n.forEach(((n,c)=>{let a=document.getElementById(n['@strife'].template);if(!a)return void console.warn('Template not found for chapter:',n['@strife'].template);let l=a.content.cloneNode(!0);l.querySelectorAll('*').forEach((e=>{[...e.attributes].forEach((s=>{if(s.name.startsWith('data-prop-')){const c=s.name.replace('data-prop-',''),a=t(c,n);a&&e.setAttribute(s.name,a)}}))})),e.appendChild(l),e.querySelectorAll(`[is^="str-"]:not([data-field^="${e.dataset.field}."])`).forEach(((a,l)=>{const d=a.dataset.field;a.dataset.field=`${e.dataset.field}.${c}.${d}`,'function'==typeof a.render?a.render(t(d,n),s):console.warn(`Field ${a.dataset.field} (${a.tagName}) does not have a render method.`)}))}))})(e,n,s);break;case'html':e.innerHTML=n;break;case'text':e.textContent=n;break;case'multi-input':((e,t,n)=>{const s=e.dataset.field.lastIndexOf('.'),c=e.dataset.field.substring(s+1);t&&Array.isArray(t)&&t.forEach((t=>{let n=document.getElementById(`multiinput_${c}`);if(n){let s=n.content.cloneNode(!0);const c=s.querySelector('[data-value]');c&&(c.textContent=t),e.appendChild(s)}}))})(e,n);break;case'assets':((e,t,n)=>{const s=e.dataset.field.lastIndexOf('.'),c=e.dataset.field.substring(s+1);t&&Array.isArray(t)&&t.forEach((t=>{let n=document.getElementById(`assets_${c}`);if(n){let s=n.content.cloneNode(!0);const c=s.querySelector('[data-name]');c&&(c.textContent=t.name);const a=s.querySelector('[data-original]');a&&(a.textContent=t.original);const l=s.querySelector('[data-thumbnail]');l&&(l.textContent=t.thumbnail);const d=s.querySelector('[data-size]');d&&(d.textContent=t.size),e.appendChild(s)}}))})(e,n);break;default:e.innerHTML=`<p>Unsupported container type: ${c} for ${e.tagName} and field ${e.dataset.field}</p>`}};customElements.define('str-div',class extends HTMLDivElement{connectedCallback(){this._cleanup=i(this)}disconnectedCallback(){this._cleanup?.()}render(e,t){r(this,e,t)}},{extends:'div'}),customElements.define('str-ul',class extends HTMLUListElement{connectedCallback(){this._cleanup=i(this)}disconnectedCallback(){this._cleanup?.()}render(e,t){r(this,e,t)}},{extends:'ul'}),customElements.define('str-ol',class extends HTMLOListElement{connectedCallback(){this._cleanup=i(this)}disconnectedCallback(){this._cleanup?.()}render(e,t){r(this,e,t)}},{extends:'ol'}),customElements.define('str-section',class extends HTMLElement{connectedCallback(){this._cleanup=i(this)}disconnectedCallback(){this._cleanup?.()}render(e,t){r(this,e,t)}},{extends:'section'}),customElements.define('str-header',class extends HTMLElement{connectedCallback(){this._cleanup=i(this)}disconnectedCallback(){this._cleanup?.()}render(e,t){r(this,e,t)}},{extends:'header'}),customElements.define('str-footer',class extends HTMLElement{connectedCallback(){this._cleanup=i(this)}disconnectedCallback(){this._cleanup?.()}render(e,t){r(this,e,t)}},{extends:'footer'}),customElements.define('str-nav',class extends HTMLElement{connectedCallback(){this._cleanup=i(this)}disconnectedCallback(){this._cleanup?.()}render(e,t){r(this,e,t)}},{extends:'nav'}),customElements.define('str-article',class extends HTMLElement{connectedCallback(){this._cleanup=i(this)}disconnectedCallback(){this._cleanup?.()}render(e,t){r(this,e,t)}},{extends:'article'}),customElements.define('str-main',class extends HTMLElement{connectedCallback(){this._cleanup=i(this)}disconnectedCallback(){this._cleanup?.()}render(e,t){r(this,e,t)}},{extends:'main'}),customElements.define('str-aside',class extends HTMLElement{connectedCallback(){this._cleanup=i(this)}disconnectedCallback(){this._cleanup?.()}render(e,t){r(this,e,t)}},{extends:'aside'}),customElements.define('str-blockquote',class extends HTMLElement{connectedCallback(){this._cleanup=i(this)}disconnectedCallback(){this._cleanup?.()}render(e,t){r(this,e,t)}},{extends:'blockquote'}),customElements.define('str-tbody',class extends HTMLTableSectionElement{connectedCallback(){this._cleanup=i(this)}disconnectedCallback(){this._cleanup?.()}render(e,t){r(this,e,t)}},{extends:'tbody'});
|
|
2
|
+
//# sourceMappingURL=index-Crin6Dn6.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index-DohBRVYp.js","sources":["../composition/anchor/index.js","../composition/picture/index.js","../composition/img/index.js","../composition/time/index.js","../../../functions/formatDate.js","../composition/text/index.js","../composition/container/render/renderChapters.js","../composition/container/index.js","../../../functions/getTypeByContext.js","../composition/container/render/renderCollection.js","../composition/container/render/renderMultiInput.js","../composition/container/render/renderAssets.js"],"sourcesContent":["import { useState } from '../../strife.js';\n\n/**\n * Client components is responsible for:\n * 1️⃣ Reacting to state changes and if needed, update the live preview.\n * 2️⃣ Send an edit signal to Wieldy with an object that is used as input parameters for the editor. The parameters are not fixed but some are e.g. status, editorName, label and tmpl\n */\n\nclass AnchorElement extends HTMLAnchorElement {\n constructor() {\n super();\n\n this.tabIndex = 0;\n }\n\n connectedCallback() {\n this._cleanup = useState(this, (state) => this.render(state));\n }\n\n disconnectedCallback() {\n this._cleanup?.();\n }\n\n render(value) {\n if (value) {\n this.href = value.href;\n const nodes = this.childNodes;\n if (nodes.length === 0) {\n this.textContent = value.text;\n } else {\n for (const node of nodes) {\n if (node.nodeType === Node.TEXT_NODE) {\n node.nodeValue = value.text;\n }\n }\n }\n if (value.target === '_blank') {\n this.target = value.target;\n }\n }\n }\n}\ncustomElements.define('str-anchor', AnchorElement, { extends: 'a' });\n","import { useState } from '../../strife.js';\n\nclass PictureElement extends HTMLPictureElement {\n constructor() {\n super();\n this.sources = [...this.querySelectorAll('source')];\n this.image = this.querySelector('img');\n }\n\n connectedCallback() {\n this._cleanup = useState(this, (state) => this.render(state));\n }\n\n disconnectedCallback() {\n this._cleanup?.();\n }\n\n render(state) {\n let hasValue = false;\n this.sources.forEach((source) => {\n source.srcset = state?.[source.dataset?.propertyMedia]?.source?.url || '';\n if (source.srcset) {\n hasValue = true;\n }\n });\n if (hasValue) {\n this.image.src = this.image.currentSrc;\n this.image.classList.remove('str-empty');\n } else {\n this.image.src = '';\n this.image.classList.add('str-empty');\n }\n }\n}\ncustomElements.define('str-picture', PictureElement, { extends: 'picture' });\n","import { useState } from '../../strife.js';\n\nclass ImageElement extends HTMLImageElement {\n constructor() {\n super();\n }\n\n connectedCallback() {\n this._cleanup = useState(this, (state) => this.render(state));\n }\n\n disconnectedCallback() {\n this._cleanup?.();\n }\n\n render(value) {\n this.src = value?.source?.url || '';\n if (this.src) {\n this.classList.remove('str-empty');\n } else {\n this.classList.add('str-empty');\n }\n }\n}\ncustomElements.define('str-img', ImageElement, { extends: 'img' });\n","import { useState } from '../../strife.js';\nimport { formatDate } from '../../../../functions/index.js';\n\n/**\n * Client components is responsible for:\n * 1️⃣ Reacting to state changes and if needed, update the live preview.\n * 2️⃣ Send an edit signal to Wieldy with an object that is used as input parameters for the editor. The parameters are not fixed but some are e.g. status, editorName, label and tmpl\n */\n\nclass TimeElement extends HTMLTimeElement {\n constructor() {\n super();\n\n this.tabIndex = 0;\n }\n\n connectedCallback() {\n this._cleanup = useState(this, (state) => this.render(state));\n }\n\n disconnectedCallback() {\n this._cleanup?.();\n }\n\n render(value) {\n if (value) {\n this.textContent = formatDate(value, this.dataset.format);\n }\n }\n}\ncustomElements.define('str-time', TimeElement, { extends: 'time' });\n","export const formatDate = (inputDate, format) => {\n if (!format) {\n return inputDate;\n }\n\n const date = new Date(inputDate);\n if (isNaN(date)) {\n return \"Invalid Date\";\n }\n\n const year = date.getFullYear();\n const shortYear = String(year).slice(-2);\n const month = String(date.getMonth() + 1).padStart(2, '0');\n const shortMonth = new Intl.DateTimeFormat('en-US', { month: 'short' }).format(date);\n const fullMonth = new Intl.DateTimeFormat('en-US', { month: 'long' }).format(date);\n const day = String(date.getDate()).padStart(2, '0');\n const shortDay = String(date.getDate());\n const hours = String(date.getHours()).padStart(2, '0');\n const minutes = String(date.getMinutes()).padStart(2, '0');\n const seconds = String(date.getSeconds()).padStart(2, '0');\n\n const replacements = {\n 'yyyy': year,\n 'yy': shortYear,\n 'MMMM': fullMonth,\n 'MMM': shortMonth,\n 'MM': month,\n 'dd': day,\n 'd': shortDay,\n 'hh': hours,\n 'mm': minutes,\n 'ss': seconds,\n };\n\n const regex = new RegExp(Object.keys(replacements).join('|'), 'g');\n\n return format.replace(regex, match => replacements[match]);\n}","import { useState } from '../../strife.js';\n\nconst init = (host) => {\n return useState(host, (state) => {\n render(host, state);\n });\n};\n\nconst render = (host, state) => {\n host.textContent = state;\n};\n\ncustomElements.define(\n 'str-address',\n class extends HTMLElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n { extends: 'address' },\n);\n\ncustomElements.define(\n 'str-p',\n class extends HTMLParagraphElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n {\n extends: 'p',\n },\n);\n\ncustomElements.define(\n 'str-span',\n class extends HTMLSpanElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n { extends: 'span' },\n);\n\ncustomElements.define(\n 'str-strong',\n class extends HTMLElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n { extends: 'strong' },\n);\n\ncustomElements.define(\n 'str-h1',\n class extends HTMLHeadingElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n { extends: 'h1' },\n);\ncustomElements.define(\n 'str-h2',\n class extends HTMLHeadingElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n {\n extends: 'h2',\n },\n);\ncustomElements.define(\n 'str-h3',\n class extends HTMLHeadingElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n {\n extends: 'h3',\n },\n);\ncustomElements.define(\n 'str-h4',\n class extends HTMLHeadingElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n {\n extends: 'h4',\n },\n);\ncustomElements.define(\n 'str-h5',\n class extends HTMLHeadingElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n {\n extends: 'h5',\n },\n);\ncustomElements.define(\n 'str-h6',\n class extends HTMLHeadingElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n {\n extends: 'h6',\n },\n);\ncustomElements.define(\n 'str-abbr',\n class extends HTMLElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n { extends: 'abbr' }\n);\ncustomElements.define(\n 'str-b',\n class extends HTMLElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n { extends: 'b' }\n);\ncustomElements.define(\n 'str-button',\n class extends HTMLButtonElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n { extends: 'button' }\n);\ncustomElements.define(\n 'str-cite',\n class extends HTMLElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n { extends: 'cite' }\n);\ncustomElements.define(\n 'str-code',\n class extends HTMLElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n { extends: 'code' }\n);\ncustomElements.define(\n 'str-dfn',\n class extends HTMLElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n { extends: 'dfn' }\n);\ncustomElements.define(\n 'str-em',\n class extends HTMLElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n { extends: 'em' }\n);\ncustomElements.define(\n 'str-i',\n class extends HTMLElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n { extends: 'i' }\n);\ncustomElements.define(\n 'str-label',\n class extends HTMLLabelElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n { extends: 'label' }\n);\ncustomElements.define(\n 'str-mark',\n class extends HTMLElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n { extends: 'mark' }\n);\ncustomElements.define(\n 'str-q',\n class extends HTMLQuoteElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n { extends: 'q' }\n);\ncustomElements.define(\n 'str-sub',\n class extends HTMLElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n { extends: 'sub' }\n);\ncustomElements.define(\n 'str-sup',\n class extends HTMLElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n { extends: 'sup' }\n);\ncustomElements.define(\n 'str-td',\n class extends HTMLTableCellElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n { extends: 'td' }\n);","import { propertyStringToValue } from '../../../../../functions/index.js';\n\nexport const renderChapters = (host, state, context) => {\n if (!state) {\n return;\n }\n state.forEach((chapter, index) => {\n let template = document.getElementById(chapter['@strife'].template);\n\n if (!template) {\n console.warn('Template not found for chapter:', chapter['@strife'].template);\n return;\n }\n\n let templateContent = template.content;\n\n let clone = templateContent.cloneNode(true);\n\n // Check and update data-prop attributes with current values\n clone.querySelectorAll('*').forEach((el) => {\n [...el.attributes].forEach((attr) => {\n if (attr.name.startsWith('data-prop-')) {\n const prop = attr.name.replace('data-prop-', '');\n const value = propertyStringToValue(prop, chapter);\n if (value) el.setAttribute(attr.name, value);\n }\n });\n });\n\n host.appendChild(clone);\n\n const components = host.querySelectorAll(`[is^=\"str-\"]:not([data-field^=\"${host.dataset.field}.\"])`);\n\n components.forEach((component, idx) => {\n const field = component.dataset.field;\n component.dataset.field = `${host.dataset.field}.${index}.${field}`;\n if (typeof component.render !== 'function') {\n console.warn(`Field ${component.dataset.field} (${component.tagName}) does not have a render method.`);\n return;\n }\n component.render(propertyStringToValue(field, chapter), context);\n });\n });\n};\n","import { useState } from '../../strife.js';\nimport { renderChapters, renderCollection, renderMultiInput, renderAssets } from './render/index.js';\nimport { getTypeByContext } from '../../../../functions/index.js';\n\nconst init = (host) => {\n return useState(host, (state, context) => {\n render(host, state, context);\n });\n};\n\nconst render = (host, state, context) => {\n // Fallback for browsers that don't support this API:\n if (true || !document.startViewTransition) {\n updateDOM(host, state, context);\n } else {\n // With a transition:\n document.startViewTransition(() => {\n updateDOM(host, state, context);\n });\n }\n};\n\nconst updateDOM = (host, state, context) => {\n let type = host.dataset.type || null;\n if (!type) {\n type = getTypeByContext(host.dataset.field, context);\n }\n host.innerHTML = '';\n switch (type) {\n case 'collection':\n renderCollection(host, state, context);\n break;\n case 'chapters':\n renderChapters(host, state, context);\n break;\n case 'html':\n host.innerHTML = state;\n break;\n case 'text':\n host.textContent = state;\n break;\n case 'multi-input':\n renderMultiInput(host, state, context);\n break;\n case 'assets':\n renderAssets(host, state, context);\n break;\n default:\n host.innerHTML = `<p>Unsupported container type: ${type} for ${host.tagName} and field ${host.dataset.field}</p>`;\n break;\n }\n};\n\ncustomElements.define(\n 'str-div',\n class extends HTMLDivElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state, context) {\n render(this, state, context);\n }\n },\n { extends: 'div' },\n);\n\ncustomElements.define(\n 'str-ul',\n class extends HTMLUListElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state, context) {\n render(this, state, context);\n }\n },\n { extends: 'ul' },\n);\n\ncustomElements.define(\n 'str-ol',\n class extends HTMLOListElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state, context) {\n render(this, state, context);\n }\n },\n { extends: 'ol' },\n);\n\ncustomElements.define(\n 'str-section',\n class extends HTMLElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state, context) {\n render(this, state, context);\n }\n },\n { extends: 'section' },\n);\n\ncustomElements.define(\n 'str-header',\n class extends HTMLElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state, context) {\n render(this, state, context);\n }\n },\n { extends: 'header' },\n);\n\ncustomElements.define(\n 'str-footer',\n class extends HTMLElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state, context) {\n render(this, state, context);\n }\n },\n { extends: 'footer' },\n);\n\ncustomElements.define(\n 'str-nav',\n class extends HTMLElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state, context) {\n render(this, state, context);\n }\n },\n { extends: 'nav' },\n);\n\ncustomElements.define(\n 'str-article',\n class extends HTMLElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state, context) {\n render(this, state, context);\n }\n },\n { extends: 'article' },\n);\n\ncustomElements.define(\n 'str-main',\n class extends HTMLElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state, context) {\n render(this, state, context);\n }\n },\n { extends: 'main' },\n);\n\ncustomElements.define(\n 'str-aside',\n class extends HTMLElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state, context) {\n render(this, state, context);\n }\n },\n { extends: 'aside' },\n);\n\ncustomElements.define(\n 'str-blockquote',\n class extends HTMLElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state, context) {\n render(this, state, context);\n }\n },\n { extends: 'blockquote' },\n);\n\ncustomElements.define(\n 'str-tbody',\n class extends HTMLTableSectionElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state, context) {\n render(this, state, context);\n }\n },\n { extends: 'tbody' },\n);\n","export const getTypeByContext = (field, context) => {\n const documentTemplate = context?.templates?.find(\n (template) => template.collection === context.model?.['@metadata']?.['@collection'],\n );\n let originProperty = field;\n if (field?.includes('.')) {\n originProperty = field.split('.')[0];\n }\n\n const templateEditorForProperty = documentTemplate?.editors?.find((e) => e.editor.propertyName === originProperty);\n const originType = templateEditorForProperty?.editor.type;\n\n if (field !== originProperty) {\n switch (originType) {\n case 'chapters':\n const [chapterIndex, chapterField] = field.split('.').slice(1);\n if (!context.draft) {\n console.warn('No draft value found in context ', context);\n return undefined;\n }\n const chapter = context.draft[originProperty]?.[Number(chapterIndex)];\n if (!chapter) return undefined;\n const chapterContentTemplate = context.templates.find(\n (template) => template.normalizedName === chapter['@strife']?.template,\n );\n const chapterEditorForProperty = chapterContentTemplate?.editors?.find(\n (e) => e.editor.propertyName === chapterField,\n );\n return chapterEditorForProperty?.editor.type;\n case 'collection':\n const [collectionIndex, collectionField] = field.split('.').slice(1);\n const collectionTemplate = context?.templates?.find(\n (template) => template.collection === context.iterate?.['@metadata']?.['@collection'],\n );\n const collectionEditorForProperty = collectionTemplate?.editors?.find(\n (e) => e.editor.propertyName === collectionField,\n );\n return collectionEditorForProperty?.editor.type;\n case 'content-template':\n const [contentTemplateField] = field.split('.').slice(1);\n const contentTemplate = context?.templates?.find(\n (template) =>\n template.normalizedName?.toLowerCase() ===\n templateEditorForProperty.editor.attributes?.templateId?.toLowerCase() ||\n template.id?.toLowerCase() === templateEditorForProperty.editor.attributes?.templateId?.toLowerCase(),\n );\n const contentTemplateEditorForProperty = contentTemplate?.editors?.find(\n (e) => e.editor.propertyName === contentTemplateField,\n );\n return contentTemplateEditorForProperty?.editor.type;\n }\n }\n\n return originType;\n};\n","import { propertyStringToValue } from '../../../../../functions/index.js';\n\nexport const renderCollection = (host, state, context) => {\n if (state.documents) {\n state.documents.forEach((doc, index) => {\n const lastIndex = host.dataset.field.lastIndexOf(\".\");\n const field = host.dataset.field.substring(lastIndex + 1);\n let template = document.getElementById(`collection_${field}`);\n\n let templateContent = template.content;\n\n host.appendChild(templateContent.cloneNode(true));\n\n const components = host.querySelectorAll(`[is^=\"str-\"]:not([data-field^=\"${host.dataset.field}.\"])`);\n\n components.forEach((component) => {\n const field = component.dataset.field;\n component.dataset.field = `${host.dataset.field}.${index}.${field}`;\n if (typeof component.render !== 'function') {\n console.warn(`Field ${component.dataset.field} (${component.tagName}) does not have a render method.`);\n return;\n }\n component.render(propertyStringToValue(field, doc), {...context, iterate: doc});\n });\n });\n }\n};\n","export const renderMultiInput = (host, state, context) => {\n const lastIndex = host.dataset.field.lastIndexOf('.');\n const field = host.dataset.field.substring(lastIndex + 1);\n if (state && Array.isArray(state)) {\n state.forEach((value) => {\n let template = document.getElementById(`multiinput_${field}`);\n if (template) {\n let clone = template.content.cloneNode(true);\n const dataValueHolder = clone.querySelector(`[data-value]`);\n if (dataValueHolder) {\n dataValueHolder.textContent = value;\n }\n host.appendChild(clone);\n }\n });\n }\n};\n","export const renderAssets = (host, state, context) => {\n const lastIndex = host.dataset.field.lastIndexOf('.');\n const field = host.dataset.field.substring(lastIndex + 1);\n if (state && Array.isArray(state)) {\n state.forEach((value) => {\n let template = document.getElementById(`assets_${field}`);\n if (template) {\n let clone = template.content.cloneNode(true);\n\n const nameHolder = clone.querySelector(`[data-name]`);\n if (nameHolder) {\n nameHolder.textContent = value.name;\n }\n\n const originalHolder = clone.querySelector(`[data-original]`);\n if (originalHolder) {\n originalHolder.textContent = value.original;\n }\n\n const thumbnailHolder = clone.querySelector(`[data-thumbnail]`);\n if (thumbnailHolder) {\n thumbnailHolder.textContent = value.thumbnail;\n }\n\n const sizeHolder = clone.querySelector(`[data-size]`);\n if (sizeHolder) {\n sizeHolder.textContent = value.size;\n }\n\n host.appendChild(clone);\n }\n });\n }\n};\n"],"names":["AnchorElement","HTMLAnchorElement","constructor","super","this","tabIndex","connectedCallback","_cleanup","useState","state","render","disconnectedCallback","value","href","nodes","childNodes","length","textContent","text","node","nodeType","Node","TEXT_NODE","nodeValue","target","customElements","define","extends","PictureElement","HTMLPictureElement","sources","querySelectorAll","image","querySelector","hasValue","forEach","source","srcset","dataset","propertyMedia","url","src","currentSrc","classList","remove","add","ImageElement","HTMLImageElement","TimeElement","HTMLTimeElement","inputDate","format","date","Date","isNaN","year","getFullYear","shortYear","String","slice","month","getMonth","padStart","shortMonth","Intl","DateTimeFormat","replacements","yyyy","yy","MMMM","MMM","MM","dd","getDate","d","hh","getHours","mm","getMinutes","ss","getSeconds","regex","RegExp","Object","keys","join","replace","match","formatDate","init","host","HTMLElement","HTMLParagraphElement","HTMLSpanElement","HTMLHeadingElement","HTMLButtonElement","HTMLLabelElement","HTMLQuoteElement","HTMLTableCellElement","context","updateDOM","type","field","documentTemplate","templates","find","template","collection","model","originProperty","includes","split","templateEditorForProperty","editors","e","editor","propertyName","originType","chapterIndex","chapterField","draft","console","warn","chapter","Number","chapterContentTemplate","normalizedName","chapterEditorForProperty","collectionIndex","collectionField","collectionTemplate","iterate","collectionEditorForProperty","contentTemplateField","contentTemplate","toLowerCase","attributes","templateId","id","contentTemplateEditorForProperty","getTypeByContext","innerHTML","documents","doc","index","lastIndex","lastIndexOf","substring","templateContent","document","getElementById","content","appendChild","cloneNode","component","propertyStringToValue","tagName","renderCollection","clone","el","attr","name","startsWith","prop","setAttribute","idx","renderChapters","Array","isArray","dataValueHolder","renderMultiInput","nameHolder","originalHolder","original","thumbnailHolder","thumbnail","sizeHolder","size","renderAssets","HTMLDivElement","HTMLUListElement","HTMLOListElement","HTMLTableSectionElement"],"mappings":"+CAQA,MAAMA,UAAsBC,kBAC1B,WAAAC,GACEC,QAEAC,KAAKC,SAAW,CAClB,CAEA,iBAAAC,GACEF,KAAKG,SAAWC,EAASJ,MAAOK,GAAUL,KAAKM,OAAOD,IACxD,CAEA,oBAAAE,GACEP,KAAKG,YACP,CAEA,MAAAG,CAAOE,GACL,GAAIA,EAAO,CACTR,KAAKS,KAAOD,EAAMC,KAClB,MAAMC,EAAQV,KAAKW,WACnB,GAAqB,IAAjBD,EAAME,OACRZ,KAAKa,YAAcL,EAAMM,UAEzB,IAAK,MAAMC,KAAQL,EACbK,EAAKC,WAAaC,KAAKC,YACzBH,EAAKI,UAAYX,EAAMM,MAIR,WAAjBN,EAAMY,SACRpB,KAAKoB,OAASZ,EAAMY,OAExB,CACF,EAEFC,eAAeC,OAAO,aAAc1B,EAAe,CAAE2B,QAAS,MCxC9D,MAAMC,UAAuBC,mBAC3B,WAAA3B,GACEC,QACAC,KAAK0B,QAAU,IAAI1B,KAAK2B,iBAAiB,WACzC3B,KAAK4B,MAAQ5B,KAAK6B,cAAc,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A,oBAAAO,GACEP,KAAKG,YACP,CACA,MAAAG,CAAOD,EAAO0F,GACZzF,EAAON,KAAMK,EAAO0F,EACtB,GAEF,CAAExE,QAAS,QAGbF,eAAeC,OACb,cACA,cAAciE,YACZ,iBAAArF,GACEF,KAAKG,SAAWkF,EAAKrF,KACvB,CACA,oBAAAO,GACEP,KAAKG,YACP,CACA,MAAAG,CAAOD,EAAO0F,GACZzF,EAAON,KAAMK,EAAO0F,EACtB,GAEF,CAAExE,QAAS,YAGbF,eAAeC,OACb,WACA,cAAciE,YACZ,iBAAArF,GACEF,KAAKG,SAAWkF,EAAKrF,KACvB,CACA,oBAAAO,GACEP,KAAKG,YACP,CACA,MAAAG,CAAOD,EAAO0F,GACZzF,EAAON,KAAMK,EAAO0F,EACtB,GAEF,CAAExE,QAAS,SAGbF,eAAeC,OACb,YACA,cAAciE,YACZ,iBAAArF,GACEF,KAAKG,SAAWkF,EAAKrF,KACvB,CACA,oBAAAO,GACEP,KAAKG,YACP,CACA,MAAAG,CAAOD,EAAO0F,GACZzF,EAAON,KAAMK,EAAO0F,EACtB,GAEF,CAAExE,QAAS,UAGbF,eAAeC,OACb,iBACA,cAAciE,YACZ,iBAAArF,GACEF,KAAKG,SAAWkF,EAAKrF,KACvB,CACA,oBAAAO,GACEP,KAAKG,YACP,CACA,MAAAG,CAAOD,EAAO0F,GACZzF,EAAON,KAAMK,EAAO0F,EACtB,GAEF,CAAExE,QAAS,eAGbF,eAAeC,OACb,YACA,cAAc4J,wBACZ,iBAAAhL,GACEF,KAAKG,SAAWkF,EAAKrF,KACvB,CACA,oBAAAO,GACEP,KAAKG,YACP,CACA,MAAAG,CAAOD,EAAO0F,GACZzF,EAAON,KAAMK,EAAO0F,EACtB,GAEF,CAAExE,QAAS"}
|
|
1
|
+
{"version":3,"file":"index-Crin6Dn6.js","sources":["../composition/anchor/index.js","../composition/picture/index.js","../composition/img/index.js","../composition/time/index.js","../../../functions/formatDate.js","../composition/text/index.js","../composition/container/render/renderChapters.js","../composition/container/index.js","../../../functions/getTypeByContext.js","../composition/container/render/renderCollection.js","../composition/container/render/renderMultiInput.js","../composition/container/render/renderAssets.js"],"sourcesContent":["import { useState } from '../../strife.js';\n\n/**\n * Client components is responsible for:\n * 1️⃣ Reacting to state changes and if needed, update the live preview.\n * 2️⃣ Send an edit signal to Wieldy with an object that is used as input parameters for the editor. The parameters are not fixed but some are e.g. status, editorName, label and tmpl\n */\n\nclass AnchorElement extends HTMLAnchorElement {\n constructor() {\n super();\n\n this.tabIndex = 0;\n }\n\n connectedCallback() {\n this._cleanup = useState(this, (state) => this.render(state));\n }\n\n disconnectedCallback() {\n this._cleanup?.();\n }\n\n render(value) {\n if (value) {\n this.href = value.href;\n const nodes = this.childNodes;\n if (nodes.length === 0) {\n this.textContent = value.text;\n } else {\n for (const node of nodes) {\n if (node.nodeType === Node.TEXT_NODE) {\n node.nodeValue = value.text;\n }\n }\n }\n if (value.target === '_blank') {\n this.target = value.target;\n }\n }\n }\n}\ncustomElements.define('str-anchor', AnchorElement, { extends: 'a' });\n","import { useState } from '../../strife.js';\n\nclass PictureElement extends HTMLPictureElement {\n constructor() {\n super();\n this.sources = [...this.querySelectorAll('source')];\n this.image = this.querySelector('img');\n }\n\n connectedCallback() {\n this._cleanup = useState(this, (state) => this.render(state));\n }\n\n disconnectedCallback() {\n this._cleanup?.();\n }\n\n render(state) {\n let hasValue = false;\n this.sources.forEach((source) => {\n source.srcset = state?.[source.dataset?.propertyMedia]?.source?.url || '';\n if (source.srcset) {\n hasValue = true;\n }\n });\n if (hasValue) {\n this.image.src = this.image.currentSrc;\n this.image.classList.remove('str-empty');\n } else {\n this.image.src = '';\n this.image.classList.add('str-empty');\n }\n }\n}\ncustomElements.define('str-picture', PictureElement, { extends: 'picture' });\n","import { useState } from '../../strife.js';\n\nclass ImageElement extends HTMLImageElement {\n constructor() {\n super();\n }\n\n connectedCallback() {\n this._cleanup = useState(this, (state) => this.render(state));\n }\n\n disconnectedCallback() {\n this._cleanup?.();\n }\n\n render(value) {\n this.src = value?.source?.url || '';\n if (this.src) {\n this.classList.remove('str-empty');\n } else {\n this.classList.add('str-empty');\n }\n }\n}\ncustomElements.define('str-img', ImageElement, { extends: 'img' });\n","import { useState } from '../../strife.js';\nimport { formatDate } from '../../../../functions/index.js';\n\n/**\n * Client components is responsible for:\n * 1️⃣ Reacting to state changes and if needed, update the live preview.\n * 2️⃣ Send an edit signal to Wieldy with an object that is used as input parameters for the editor. The parameters are not fixed but some are e.g. status, editorName, label and tmpl\n */\n\nclass TimeElement extends HTMLTimeElement {\n constructor() {\n super();\n\n this.tabIndex = 0;\n }\n\n connectedCallback() {\n this._cleanup = useState(this, (state) => this.render(state));\n }\n\n disconnectedCallback() {\n this._cleanup?.();\n }\n\n render(value) {\n if (value) {\n this.textContent = formatDate(value, this.dataset.format);\n }\n }\n}\ncustomElements.define('str-time', TimeElement, { extends: 'time' });\n","export const formatDate = (inputDate, format) => {\n if (!format) {\n return inputDate;\n }\n\n const date = new Date(inputDate);\n if (isNaN(date)) {\n return \"Invalid Date\";\n }\n\n const year = date.getFullYear();\n const shortYear = String(year).slice(-2);\n const month = String(date.getMonth() + 1).padStart(2, '0');\n const shortMonth = new Intl.DateTimeFormat('en-US', { month: 'short' }).format(date);\n const fullMonth = new Intl.DateTimeFormat('en-US', { month: 'long' }).format(date);\n const day = String(date.getDate()).padStart(2, '0');\n const shortDay = String(date.getDate());\n const hours = String(date.getHours()).padStart(2, '0');\n const minutes = String(date.getMinutes()).padStart(2, '0');\n const seconds = String(date.getSeconds()).padStart(2, '0');\n\n const replacements = {\n 'yyyy': year,\n 'yy': shortYear,\n 'MMMM': fullMonth,\n 'MMM': shortMonth,\n 'MM': month,\n 'dd': day,\n 'd': shortDay,\n 'hh': hours,\n 'mm': minutes,\n 'ss': seconds,\n };\n\n const regex = new RegExp(Object.keys(replacements).join('|'), 'g');\n\n return format.replace(regex, match => replacements[match]);\n}","import { useState } from '../../strife.js';\n\nconst init = (host) => {\n return useState(host, (state) => {\n render(host, state);\n });\n};\n\nconst render = (host, state) => {\n host.textContent = state;\n};\n\ncustomElements.define(\n 'str-address',\n class extends HTMLElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n { extends: 'address' },\n);\n\ncustomElements.define(\n 'str-p',\n class extends HTMLParagraphElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n {\n extends: 'p',\n },\n);\n\ncustomElements.define(\n 'str-span',\n class extends HTMLSpanElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n { extends: 'span' },\n);\n\ncustomElements.define(\n 'str-strong',\n class extends HTMLElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n { extends: 'strong' },\n);\n\ncustomElements.define(\n 'str-h1',\n class extends HTMLHeadingElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n { extends: 'h1' },\n);\ncustomElements.define(\n 'str-h2',\n class extends HTMLHeadingElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n {\n extends: 'h2',\n },\n);\ncustomElements.define(\n 'str-h3',\n class extends HTMLHeadingElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n {\n extends: 'h3',\n },\n);\ncustomElements.define(\n 'str-h4',\n class extends HTMLHeadingElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n {\n extends: 'h4',\n },\n);\ncustomElements.define(\n 'str-h5',\n class extends HTMLHeadingElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n {\n extends: 'h5',\n },\n);\ncustomElements.define(\n 'str-h6',\n class extends HTMLHeadingElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n {\n extends: 'h6',\n },\n);\ncustomElements.define(\n 'str-abbr',\n class extends HTMLElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n { extends: 'abbr' }\n);\ncustomElements.define(\n 'str-b',\n class extends HTMLElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n { extends: 'b' }\n);\ncustomElements.define(\n 'str-button',\n class extends HTMLButtonElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n { extends: 'button' }\n);\ncustomElements.define(\n 'str-cite',\n class extends HTMLElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n { extends: 'cite' }\n);\ncustomElements.define(\n 'str-code',\n class extends HTMLElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n { extends: 'code' }\n);\ncustomElements.define(\n 'str-dfn',\n class extends HTMLElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n { extends: 'dfn' }\n);\ncustomElements.define(\n 'str-em',\n class extends HTMLElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n { extends: 'em' }\n);\ncustomElements.define(\n 'str-i',\n class extends HTMLElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n { extends: 'i' }\n);\ncustomElements.define(\n 'str-label',\n class extends HTMLLabelElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n { extends: 'label' }\n);\ncustomElements.define(\n 'str-mark',\n class extends HTMLElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n { extends: 'mark' }\n);\ncustomElements.define(\n 'str-q',\n class extends HTMLQuoteElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n { extends: 'q' }\n);\ncustomElements.define(\n 'str-sub',\n class extends HTMLElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n { extends: 'sub' }\n);\ncustomElements.define(\n 'str-sup',\n class extends HTMLElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n { extends: 'sup' }\n);\ncustomElements.define(\n 'str-td',\n class extends HTMLTableCellElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state) {\n render(this, state);\n }\n },\n { extends: 'td' }\n);","import { propertyStringToValue } from '../../../../../functions/index.js';\n\nexport const renderChapters = (host, state, context) => {\n if (!state) {\n return;\n }\n state.forEach((chapter, index) => {\n let template = document.getElementById(chapter['@strife'].template);\n\n if (!template) {\n console.warn('Template not found for chapter:', chapter['@strife'].template);\n return;\n }\n\n let templateContent = template.content;\n\n let clone = templateContent.cloneNode(true);\n\n // Check and update data-prop attributes with current values\n clone.querySelectorAll('*').forEach((el) => {\n [...el.attributes].forEach((attr) => {\n if (attr.name.startsWith('data-prop-')) {\n const prop = attr.name.replace('data-prop-', '');\n const value = propertyStringToValue(prop, chapter);\n if (value) el.setAttribute(attr.name, value);\n }\n });\n });\n\n host.appendChild(clone);\n\n const components = host.querySelectorAll(`[is^=\"str-\"]:not([data-field^=\"${host.dataset.field}.\"])`);\n\n components.forEach((component, idx) => {\n const field = component.dataset.field;\n component.dataset.field = `${host.dataset.field}.${index}.${field}`;\n if (typeof component.render !== 'function') {\n console.warn(`Field ${component.dataset.field} (${component.tagName}) does not have a render method.`);\n return;\n }\n component.render(propertyStringToValue(field, chapter), context);\n });\n });\n};\n","import { useState } from '../../strife.js';\nimport { renderChapters, renderCollection, renderMultiInput, renderAssets } from './render/index.js';\nimport { getTypeByContext } from '../../../../functions/index.js';\n\nconst init = (host) => {\n return useState(host, (state, context) => {\n render(host, state, context);\n });\n};\n\nconst render = (host, state, context) => {\n // Fallback for browsers that don't support this API:\n if (true || !document.startViewTransition) {\n updateDOM(host, state, context);\n } else {\n // With a transition:\n document.startViewTransition(() => {\n updateDOM(host, state, context);\n });\n }\n};\n\nconst updateDOM = (host, state, context) => {\n let type = host.dataset.type || null;\n if (!type) {\n type = getTypeByContext(host.dataset.field, context);\n }\n host.innerHTML = '';\n switch (type) {\n case 'collection':\n renderCollection(host, state, context);\n break;\n case 'chapters':\n renderChapters(host, state, context);\n break;\n case 'html':\n host.innerHTML = state;\n break;\n case 'text':\n host.textContent = state;\n break;\n case 'multi-input':\n renderMultiInput(host, state, context);\n break;\n case 'assets':\n renderAssets(host, state, context);\n break;\n default:\n host.innerHTML = `<p>Unsupported container type: ${type} for ${host.tagName} and field ${host.dataset.field}</p>`;\n break;\n }\n};\n\ncustomElements.define(\n 'str-div',\n class extends HTMLDivElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state, context) {\n render(this, state, context);\n }\n },\n { extends: 'div' },\n);\n\ncustomElements.define(\n 'str-ul',\n class extends HTMLUListElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state, context) {\n render(this, state, context);\n }\n },\n { extends: 'ul' },\n);\n\ncustomElements.define(\n 'str-ol',\n class extends HTMLOListElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state, context) {\n render(this, state, context);\n }\n },\n { extends: 'ol' },\n);\n\ncustomElements.define(\n 'str-section',\n class extends HTMLElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state, context) {\n render(this, state, context);\n }\n },\n { extends: 'section' },\n);\n\ncustomElements.define(\n 'str-header',\n class extends HTMLElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state, context) {\n render(this, state, context);\n }\n },\n { extends: 'header' },\n);\n\ncustomElements.define(\n 'str-footer',\n class extends HTMLElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state, context) {\n render(this, state, context);\n }\n },\n { extends: 'footer' },\n);\n\ncustomElements.define(\n 'str-nav',\n class extends HTMLElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state, context) {\n render(this, state, context);\n }\n },\n { extends: 'nav' },\n);\n\ncustomElements.define(\n 'str-article',\n class extends HTMLElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state, context) {\n render(this, state, context);\n }\n },\n { extends: 'article' },\n);\n\ncustomElements.define(\n 'str-main',\n class extends HTMLElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state, context) {\n render(this, state, context);\n }\n },\n { extends: 'main' },\n);\n\ncustomElements.define(\n 'str-aside',\n class extends HTMLElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state, context) {\n render(this, state, context);\n }\n },\n { extends: 'aside' },\n);\n\ncustomElements.define(\n 'str-blockquote',\n class extends HTMLElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state, context) {\n render(this, state, context);\n }\n },\n { extends: 'blockquote' },\n);\n\ncustomElements.define(\n 'str-tbody',\n class extends HTMLTableSectionElement {\n connectedCallback() {\n this._cleanup = init(this);\n }\n disconnectedCallback() {\n this._cleanup?.();\n }\n render(state, context) {\n render(this, state, context);\n }\n },\n { extends: 'tbody' },\n);\n","export const getTypeByContext = (field, context) => {\n const documentTemplate = context?.templates?.find(\n (template) => template.collection === context.model?.['@metadata']?.['@collection'],\n );\n let originProperty = field;\n if (field?.includes('.')) {\n originProperty = field.split('.')[0];\n }\n\n const templateEditorForProperty = documentTemplate?.editors?.find((e) => e.editor.propertyName === originProperty);\n const originType = templateEditorForProperty?.editor.type;\n\n if (field !== originProperty) {\n switch (originType) {\n case 'chapters':\n const [chapterIndex, chapterField] = field.split('.').slice(1);\n if (!context.draft) {\n console.warn('No draft value found in context ', context);\n return undefined;\n }\n const chapter = context.draft[originProperty]?.[Number(chapterIndex)];\n if (!chapter) return undefined;\n const chapterContentTemplate = context.templates.find(\n (template) => template.normalizedName === chapter['@strife']?.template,\n );\n const chapterEditorForProperty = chapterContentTemplate?.editors?.find(\n (e) => e.editor.propertyName === chapterField,\n );\n return chapterEditorForProperty?.editor.type;\n case 'collection':\n const [collectionIndex, collectionField] = field.split('.').slice(1);\n const collectionTemplate = context?.templates?.find(\n (template) => template.collection === context.iterate?.['@metadata']?.['@collection'],\n );\n const collectionEditorForProperty = collectionTemplate?.editors?.find(\n (e) => e.editor.propertyName === collectionField,\n );\n return collectionEditorForProperty?.editor.type;\n case 'content-template':\n const [contentTemplateField] = field.split('.').slice(1);\n const contentTemplate = context?.templates?.find(\n (template) =>\n template.normalizedName?.toLowerCase() ===\n templateEditorForProperty.editor.attributes?.templateId?.toLowerCase() ||\n template.id?.toLowerCase() === templateEditorForProperty.editor.attributes?.templateId?.toLowerCase(),\n );\n const contentTemplateEditorForProperty = contentTemplate?.editors?.find(\n (e) => e.editor.propertyName === contentTemplateField,\n );\n return contentTemplateEditorForProperty?.editor.type;\n }\n }\n\n return originType;\n};\n","import { propertyStringToValue } from '../../../../../functions/index.js';\n\nexport const renderCollection = (host, state, context) => {\n if (state.documents) {\n state.documents.forEach((doc, index) => {\n const lastIndex = host.dataset.field.lastIndexOf(\".\");\n const field = host.dataset.field.substring(lastIndex + 1);\n let template = document.getElementById(`collection_${field}`);\n\n let templateContent = template.content;\n\n host.appendChild(templateContent.cloneNode(true));\n\n const components = host.querySelectorAll(`[is^=\"str-\"]:not([data-field^=\"${host.dataset.field}.\"])`);\n\n components.forEach((component) => {\n const field = component.dataset.field;\n component.dataset.field = `${host.dataset.field}.${index}.${field}`;\n if (typeof component.render !== 'function') {\n console.warn(`Field ${component.dataset.field} (${component.tagName}) does not have a render method.`);\n return;\n }\n component.render(propertyStringToValue(field, doc), {...context, iterate: doc});\n });\n });\n }\n};\n","export const renderMultiInput = (host, state, context) => {\n const lastIndex = host.dataset.field.lastIndexOf('.');\n const field = host.dataset.field.substring(lastIndex + 1);\n if (state && Array.isArray(state)) {\n state.forEach((value) => {\n let template = document.getElementById(`multiinput_${field}`);\n if (template) {\n let clone = template.content.cloneNode(true);\n const dataValueHolder = clone.querySelector(`[data-value]`);\n if (dataValueHolder) {\n dataValueHolder.textContent = value;\n }\n host.appendChild(clone);\n }\n });\n }\n};\n","export const renderAssets = (host, state, context) => {\n const lastIndex = host.dataset.field.lastIndexOf('.');\n const field = host.dataset.field.substring(lastIndex + 1);\n if (state && Array.isArray(state)) {\n state.forEach((value) => {\n let template = document.getElementById(`assets_${field}`);\n if (template) {\n let clone = template.content.cloneNode(true);\n\n const nameHolder = clone.querySelector(`[data-name]`);\n if (nameHolder) {\n nameHolder.textContent = value.name;\n }\n\n const originalHolder = clone.querySelector(`[data-original]`);\n if (originalHolder) {\n originalHolder.textContent = value.original;\n }\n\n const thumbnailHolder = clone.querySelector(`[data-thumbnail]`);\n if (thumbnailHolder) {\n thumbnailHolder.textContent = value.thumbnail;\n }\n\n const sizeHolder = clone.querySelector(`[data-size]`);\n if (sizeHolder) {\n sizeHolder.textContent = value.size;\n }\n\n host.appendChild(clone);\n }\n });\n }\n};\n"],"names":["AnchorElement","HTMLAnchorElement","constructor","super","this","tabIndex","connectedCallback","_cleanup","useState","state","render","disconnectedCallback","value","href","nodes","childNodes","length","textContent","text","node","nodeType","Node","TEXT_NODE","nodeValue","target","customElements","define","extends","PictureElement","HTMLPictureElement","sources","querySelectorAll","image","querySelector","hasValue","forEach","source","srcset","dataset","propertyMedia","url","src","currentSrc","classList","remove","add","ImageElement","HTMLImageElement","TimeElement","HTMLTimeElement","inputDate","format","date","Date","isNaN","year","getFullYear","shortYear","String","slice","month","getMonth","padStart","shortMonth","Intl","DateTimeFormat","replacements","yyyy","yy","MMMM","MMM","MM","dd","getDate","d","hh","getHours","mm","getMinutes","ss","getSeconds","regex","RegExp","Object","keys","join","replace","match","formatDate","init","host","HTMLElement","HTMLParagraphElement","HTMLSpanElement","HTMLHeadingElement","HTMLButtonElement","HTMLLabelElement","HTMLQuoteElement","HTMLTableCellElement","context","updateDOM","type","field","documentTemplate","templates","find","template","collection","model","originProperty","includes","split","templateEditorForProperty","editors","e","editor","propertyName","originType","chapterIndex","chapterField","draft","console","warn","chapter","Number","chapterContentTemplate","normalizedName","chapterEditorForProperty","collectionIndex","collectionField","collectionTemplate","iterate","collectionEditorForProperty","contentTemplateField","contentTemplate","toLowerCase","attributes","templateId","id","contentTemplateEditorForProperty","getTypeByContext","innerHTML","documents","doc","index","lastIndex","lastIndexOf","substring","templateContent","document","getElementById","content","appendChild","cloneNode","component","propertyStringToValue","tagName","renderCollection","clone","el","attr","name","startsWith","prop","setAttribute","idx","renderChapters","Array","isArray","dataValueHolder","renderMultiInput","nameHolder","originalHolder","original","thumbnailHolder","thumbnail","sizeHolder","size","renderAssets","HTMLDivElement","HTMLUListElement","HTMLOListElement","HTMLTableSectionElement"],"mappings":"+CAQA,MAAMA,UAAsBC,kBAC1B,WAAAC,GACEC,QAEAC,KAAKC,SAAW,CAClB,CAEA,iBAAAC,GACEF,KAAKG,SAAWC,EAASJ,MAAOK,GAAUL,KAAKM,OAAOD,IACxD,CAEA,oBAAAE,GACEP,KAAKG,YACP,CAEA,MAAAG,CAAOE,GACL,GAAIA,EAAO,CACTR,KAAKS,KAAOD,EAAMC,KAClB,MAAMC,EAAQV,KAAKW,WACnB,GAAqB,IAAjBD,EAAME,OACRZ,KAAKa,YAAcL,EAAMM,UAEzB,IAAK,MAAMC,KAAQL,EACbK,EAAKC,WAAaC,KAAKC,YACzBH,EAAKI,UAAYX,EAAMM,MAIR,WAAjBN,EAAMY,SACRpB,KAAKoB,OAASZ,EAAMY,OAExB,CACF,EAEFC,eAAeC,OAAO,aAAc1B,EAAe,CAAE2B,QAAS,MCxC9D,MAAMC,UAAuBC,mBAC3B,WAAA3B,GACEC,QACAC,KAAK0B,QAAU,IAAI1B,KAAK2B,iBAAiB,WACzC3B,KAAK4B,MAAQ5B,KAAK6B,cAAc,MAClC,CAEA,iBAAA3B,GACEF,KAAKG,SAAWC,EAASJ,MAAOK,GAAUL,KAAKM,OAAOD,IACxD,CAEA,oBAAAE,GACEP,KAAKG,YACP,CAEA,MAAAG,CAAOD,GACL,IAAIyB,GAAW,EACf9B,KAAK0B,QAAQK,SAASC,IACpBA,EAAOC,OAAS5B,IAAQ2B,EAAOE,SAASC,gBAAgBH,QAAQI,KAAO,GACnEJ,EAAOC,SACTH,GAAW,EACb,IAEEA,G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AExE,QAAS,YAGbF,eAAeC,OACb,WACA,cAAciE,YACZ,iBAAArF,GACEF,KAAKG,SAAWkF,EAAKrF,KACvB,CACA,oBAAAO,GACEP,KAAKG,YACP,CACA,MAAAG,CAAOD,EAAO0F,GACZzF,EAAON,KAAMK,EAAO0F,EACtB,GAEF,CAAExE,QAAS,SAGbF,eAAeC,OACb,YACA,cAAciE,YACZ,iBAAArF,GACEF,KAAKG,SAAWkF,EAAKrF,KACvB,CACA,oBAAAO,GACEP,KAAKG,YACP,CACA,MAAAG,CAAOD,EAAO0F,GACZzF,EAAON,KAAMK,EAAO0F,EACtB,GAEF,CAAExE,QAAS,UAGbF,eAAeC,OACb,iBACA,cAAciE,YACZ,iBAAArF,GACEF,KAAKG,SAAWkF,EAAKrF,KACvB,CACA,oBAAAO,GACEP,KAAKG,YACP,CACA,MAAAG,CAAOD,EAAO0F,GACZzF,EAAON,KAAMK,EAAO0F,EACtB,GAEF,CAAExE,QAAS,eAGbF,eAAeC,OACb,YACA,cAAc4J,wBACZ,iBAAAhL,GACEF,KAAKG,SAAWkF,EAAKrF,KACvB,CACA,oBAAAO,GACEP,KAAKG,YACP,CACA,MAAAG,CAAOD,EAAO0F,GACZzF,EAAON,KAAMK,EAAO0F,EACtB,GAEF,CAAExE,QAAS"}
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{s as subscribe,u as useState}from'./index-
|
|
1
|
+
export{s as subscribe,u as useState}from'./index-BIjDe1U1.js';
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Codec for the single `STRIFE_SECRET` env var.
|
|
3
|
+
*
|
|
4
|
+
* Wire format (dot-separated, JWT-style): `v1.<meta>.<cert>`
|
|
5
|
+
* - `meta` = base64url(JSON.stringify({ urls, database, password?, type?, teamId?, previewSecret? }))
|
|
6
|
+
* - `cert` = base64url(<raw PFX bytes>) — encoded ONCE (no double-base64)
|
|
7
|
+
*
|
|
8
|
+
* This module is the single source of truth for the format. Producers (the CLI
|
|
9
|
+
* `create`/provisioning flow, generation scripts) and consumers (the generated
|
|
10
|
+
* `strife:store` module, edit-mode) both bind to it. It is intentionally
|
|
11
|
+
* dependency-free (Node `Buffer` only) so the decode logic runs on every
|
|
12
|
+
* Node-based runtime, including edge runtimes without `node:zlib`. No
|
|
13
|
+
* compression, no encryption — base64url is encoding, not secrecy.
|
|
14
|
+
*
|
|
15
|
+
* Error messages carry only STRUCTURAL diagnostics — never the blob value, the
|
|
16
|
+
* decoded meta, the certificate bytes, or the password (R7 no-leak): a decode
|
|
17
|
+
* error can surface in an SSR log or error overlay.
|
|
18
|
+
*/
|
|
19
|
+
export interface PackedSecrets {
|
|
20
|
+
urls: string[];
|
|
21
|
+
database: string;
|
|
22
|
+
/** Raw PFX bytes (NOT base64). RavenDB receives this Buffer directly. */
|
|
23
|
+
certificate: Buffer;
|
|
24
|
+
password?: string;
|
|
25
|
+
type?: string;
|
|
26
|
+
/**
|
|
27
|
+
* Team/workspace id. Matched against the `workspace` claim of a preview
|
|
28
|
+
* (edit-mode) token. Not secret on its own — an identifier, like an account
|
|
29
|
+
* number.
|
|
30
|
+
*/
|
|
31
|
+
teamId?: string;
|
|
32
|
+
/**
|
|
33
|
+
* HMAC secret used to verify preview (edit-mode) tokens. Distinct in purpose
|
|
34
|
+
* from the DB certificate/password, but rides in the same blob so consumers
|
|
35
|
+
* configure a single var. Consumed by edit-mode.ts.
|
|
36
|
+
*/
|
|
37
|
+
previewSecret?: string;
|
|
38
|
+
}
|
|
39
|
+
/** Thrown on a malformed blob. Messages are structural-only (no secret content). */
|
|
40
|
+
export declare class SecretsDecodeError extends Error {
|
|
41
|
+
constructor(message: string);
|
|
42
|
+
}
|
|
43
|
+
export declare function encodeSecrets(secrets: PackedSecrets): string;
|
|
44
|
+
/**
|
|
45
|
+
* Decode a `STRIFE_SECRET` blob.
|
|
46
|
+
*
|
|
47
|
+
* @returns the packed secrets, or `null` when the blob carries a *known-shape*
|
|
48
|
+
* but unrecognised version (e.g. a future `v2`). `null` signals the caller to
|
|
49
|
+
* treat `STRIFE_SECRET` as unset and degrade to the four-var fallback chain,
|
|
50
|
+
* rather than aborting module init.
|
|
51
|
+
* @throws {SecretsDecodeError} when the blob is malformed (wrong section count,
|
|
52
|
+
* no version prefix, bad base64url, invalid/incomplete JSON).
|
|
53
|
+
*/
|
|
54
|
+
export declare function decodeSecrets(value: string): PackedSecrets | null;
|
package/dist/secrets.js
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Codec for the single `STRIFE_SECRET` env var.
|
|
3
|
+
*
|
|
4
|
+
* Wire format (dot-separated, JWT-style): `v1.<meta>.<cert>`
|
|
5
|
+
* - `meta` = base64url(JSON.stringify({ urls, database, password?, type?, teamId?, previewSecret? }))
|
|
6
|
+
* - `cert` = base64url(<raw PFX bytes>) — encoded ONCE (no double-base64)
|
|
7
|
+
*
|
|
8
|
+
* This module is the single source of truth for the format. Producers (the CLI
|
|
9
|
+
* `create`/provisioning flow, generation scripts) and consumers (the generated
|
|
10
|
+
* `strife:store` module, edit-mode) both bind to it. It is intentionally
|
|
11
|
+
* dependency-free (Node `Buffer` only) so the decode logic runs on every
|
|
12
|
+
* Node-based runtime, including edge runtimes without `node:zlib`. No
|
|
13
|
+
* compression, no encryption — base64url is encoding, not secrecy.
|
|
14
|
+
*
|
|
15
|
+
* Error messages carry only STRUCTURAL diagnostics — never the blob value, the
|
|
16
|
+
* decoded meta, the certificate bytes, or the password (R7 no-leak): a decode
|
|
17
|
+
* error can surface in an SSR log or error overlay.
|
|
18
|
+
*/
|
|
19
|
+
const VERSION = 'v1';
|
|
20
|
+
/** base64url alphabet, no padding — exactly what `Buffer.toString('base64url')` emits. */
|
|
21
|
+
const BASE64URL = /^[A-Za-z0-9_-]+$/;
|
|
22
|
+
/** Thrown on a malformed blob. Messages are structural-only (no secret content). */
|
|
23
|
+
export class SecretsDecodeError extends Error {
|
|
24
|
+
constructor(message) {
|
|
25
|
+
super(`STRIFE_SECRET: ${message}`);
|
|
26
|
+
this.name = 'SecretsDecodeError';
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
export function encodeSecrets(secrets) {
|
|
30
|
+
const meta = {
|
|
31
|
+
urls: secrets.urls,
|
|
32
|
+
database: secrets.database,
|
|
33
|
+
};
|
|
34
|
+
// Omit empty optional fields to save bytes; decode restores absence faithfully.
|
|
35
|
+
if (secrets.password)
|
|
36
|
+
meta.password = secrets.password;
|
|
37
|
+
if (secrets.type)
|
|
38
|
+
meta.type = secrets.type;
|
|
39
|
+
if (secrets.teamId)
|
|
40
|
+
meta.teamId = secrets.teamId;
|
|
41
|
+
if (secrets.previewSecret)
|
|
42
|
+
meta.previewSecret = secrets.previewSecret;
|
|
43
|
+
const metaB64 = Buffer.from(JSON.stringify(meta), 'utf8').toString('base64url');
|
|
44
|
+
const certB64 = secrets.certificate.toString('base64url');
|
|
45
|
+
return `${VERSION}.${metaB64}.${certB64}`;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Decode a `STRIFE_SECRET` blob.
|
|
49
|
+
*
|
|
50
|
+
* @returns the packed secrets, or `null` when the blob carries a *known-shape*
|
|
51
|
+
* but unrecognised version (e.g. a future `v2`). `null` signals the caller to
|
|
52
|
+
* treat `STRIFE_SECRET` as unset and degrade to the four-var fallback chain,
|
|
53
|
+
* rather than aborting module init.
|
|
54
|
+
* @throws {SecretsDecodeError} when the blob is malformed (wrong section count,
|
|
55
|
+
* no version prefix, bad base64url, invalid/incomplete JSON).
|
|
56
|
+
*/
|
|
57
|
+
export function decodeSecrets(value) {
|
|
58
|
+
const sections = value.split('.');
|
|
59
|
+
if (sections.length !== 3) {
|
|
60
|
+
throw new SecretsDecodeError(`expected 3 dot-separated sections, got ${sections.length}`);
|
|
61
|
+
}
|
|
62
|
+
const [version, metaB64, certB64] = sections;
|
|
63
|
+
if (version !== VERSION) {
|
|
64
|
+
// A future versioned blob (vN, N != 1) we do not know how to read → treat as
|
|
65
|
+
// unset so resolution falls back to the individual STRIFE_* vars / options.
|
|
66
|
+
if (/^v\d+$/.test(version))
|
|
67
|
+
return null;
|
|
68
|
+
throw new SecretsDecodeError('unrecognised format (missing version prefix)');
|
|
69
|
+
}
|
|
70
|
+
if (!BASE64URL.test(metaB64)) {
|
|
71
|
+
throw new SecretsDecodeError('meta section is not valid base64url');
|
|
72
|
+
}
|
|
73
|
+
if (!BASE64URL.test(certB64)) {
|
|
74
|
+
throw new SecretsDecodeError('cert section is not valid base64url');
|
|
75
|
+
}
|
|
76
|
+
let meta;
|
|
77
|
+
try {
|
|
78
|
+
meta = JSON.parse(Buffer.from(metaB64, 'base64url').toString('utf8'));
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
// Swallow the original error — it can quote the malformed (secret-bearing) input.
|
|
82
|
+
throw new SecretsDecodeError('meta section is not valid JSON');
|
|
83
|
+
}
|
|
84
|
+
if (typeof meta !== 'object' ||
|
|
85
|
+
meta === null ||
|
|
86
|
+
!Array.isArray(meta.urls) ||
|
|
87
|
+
typeof meta.database !== 'string') {
|
|
88
|
+
throw new SecretsDecodeError('meta section missing required fields (urls, database)');
|
|
89
|
+
}
|
|
90
|
+
const m = meta;
|
|
91
|
+
const result = {
|
|
92
|
+
urls: m.urls,
|
|
93
|
+
database: m.database,
|
|
94
|
+
certificate: Buffer.from(certB64, 'base64url'),
|
|
95
|
+
};
|
|
96
|
+
if (m.password !== undefined)
|
|
97
|
+
result.password = m.password;
|
|
98
|
+
if (m.type !== undefined)
|
|
99
|
+
result.type = m.type;
|
|
100
|
+
if (m.teamId !== undefined)
|
|
101
|
+
result.teamId = m.teamId;
|
|
102
|
+
if (m.previewSecret !== undefined)
|
|
103
|
+
result.previewSecret = m.previewSecret;
|
|
104
|
+
return result;
|
|
105
|
+
}
|
package/package.json
CHANGED
|
@@ -1,23 +1,65 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@strifeapp/strife",
|
|
3
|
-
"version": "1.
|
|
4
|
-
"
|
|
3
|
+
"version": "1.1.0",
|
|
4
|
+
"publishConfig": {
|
|
5
|
+
"access": "public"
|
|
6
|
+
},
|
|
7
|
+
"description": "The Strife SDK — content-preview runtime plus schema authoring, the versioned content-index, types, and the STRIFE_SECRET codec for a Strife-backed site.",
|
|
5
8
|
"type": "module",
|
|
6
9
|
"keywords": [],
|
|
7
10
|
"files": [
|
|
8
|
-
"dist"
|
|
11
|
+
"dist",
|
|
12
|
+
"schema.js",
|
|
13
|
+
"schema.d.ts",
|
|
14
|
+
"types.js",
|
|
15
|
+
"types.d.ts",
|
|
16
|
+
"content-index.d.ts"
|
|
9
17
|
],
|
|
10
18
|
"source": "index.js",
|
|
11
19
|
"module": "dist/index.js",
|
|
12
20
|
"unpkg": "dist/index.js",
|
|
21
|
+
"exports": {
|
|
22
|
+
".": {
|
|
23
|
+
"import": "./dist/index.js",
|
|
24
|
+
"default": "./dist/index.js"
|
|
25
|
+
},
|
|
26
|
+
"./schema": {
|
|
27
|
+
"types": "./schema.d.ts",
|
|
28
|
+
"import": "./schema.js",
|
|
29
|
+
"default": "./schema.js"
|
|
30
|
+
},
|
|
31
|
+
"./types": {
|
|
32
|
+
"types": "./types.d.ts",
|
|
33
|
+
"import": "./types.js",
|
|
34
|
+
"default": "./types.js"
|
|
35
|
+
},
|
|
36
|
+
"./secrets": {
|
|
37
|
+
"types": "./dist/secrets.d.ts",
|
|
38
|
+
"import": "./dist/secrets.js",
|
|
39
|
+
"default": "./dist/secrets.js"
|
|
40
|
+
},
|
|
41
|
+
"./content-index": {
|
|
42
|
+
"types": "./content-index.d.ts",
|
|
43
|
+
"import": "./dist/content-index.js",
|
|
44
|
+
"default": "./dist/content-index.js"
|
|
45
|
+
}
|
|
46
|
+
},
|
|
13
47
|
"scripts": {
|
|
14
|
-
"build": "
|
|
48
|
+
"build": "npm run clean && rollup -c -i index.js -d dist && tsc -p tsconfig.build.json && node scripts/gen-content-index.mjs",
|
|
49
|
+
"test": "vitest run",
|
|
15
50
|
"prepublishOnly": "npm run clean && npm run build",
|
|
16
51
|
"clean": "rimraf dist"
|
|
17
52
|
},
|
|
53
|
+
"dependencies": {
|
|
54
|
+
"@strifeapp/schema": "^0.1.0",
|
|
55
|
+
"@strifeapp/types": "^0.1.0"
|
|
56
|
+
},
|
|
18
57
|
"devDependencies": {
|
|
19
58
|
"@rollup/plugin-terser": "^1.0.0",
|
|
59
|
+
"@types/node": "^22.7.5",
|
|
20
60
|
"rimraf": "^6.1.3",
|
|
21
|
-
"rollup": "^4.0.0"
|
|
61
|
+
"rollup": "^4.0.0",
|
|
62
|
+
"typescript": "^5.7.3",
|
|
63
|
+
"vitest": "^2.1.9"
|
|
22
64
|
}
|
|
23
65
|
}
|
package/schema.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from '@strifeapp/schema';
|
package/schema.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// Umbrella subpath: re-export the build-time schema authoring + codegen surface.
|
|
2
|
+
// One pinned @strifeapp/strife version governs the whole site, including the DSL.
|
|
3
|
+
// Node/build-time only (jiti/tinyglobby live behind @strifeapp/schema) — never
|
|
4
|
+
// imported by the browser preview entry (`.`).
|
|
5
|
+
export * from '@strifeapp/schema';
|
package/types.d.ts
ADDED
package/types.js
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// Umbrella subpath (runtime): re-export @strifeapp/types. The source is type-only,
|
|
2
|
+
// so this is an effectively empty runtime module — it exists so the subpath resolves
|
|
3
|
+
// as a normal module for TS/bundlers (the `types` condition supplies the declarations).
|
|
4
|
+
export * from '@strifeapp/types';
|