@bitcobblers/wod-wiki-engine 0.53.2204 → 0.54.2205
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/dist/agent.cjs +6426 -0
- package/dist/agent.cjs.map +1 -0
- package/dist/agent.d.cts +851 -0
- package/dist/agent.d.ts +851 -0
- package/dist/agent.mjs +2701 -0
- package/dist/agent.mjs.map +1 -0
- package/dist/chunk-FSWOTQ5M.mjs +4492 -0
- package/dist/chunk-FSWOTQ5M.mjs.map +1 -0
- package/dist/index.cjs +6 -6
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +17 -370
- package/dist/index.d.ts +17 -370
- package/dist/index.mjs +4 -4493
- package/dist/index.mjs.map +1 -1
- package/dist/ir-CKImc4T0.d.cts +360 -0
- package/dist/ir-CKImc4T0.d.ts +360 -0
- package/package.json +13 -7
package/dist/index.mjs
CHANGED
|
@@ -1,12 +1,9 @@
|
|
|
1
|
-
|
|
1
|
+
export { APP_ORIGIN, BUILD_TIME, CANVAS_CHUNK_ID, DASHBOARDS_CHUNK_ID, DirectoryHandleFeedTree, EFFORTS_CHUNK_ID, EQUIPMENT_CHUNK_ID, FeedTreeError, GIT_SHA, HttpFeedTree, MemoryFeedTree, NOTE_ID_FRONTMATTER_KEY, PUBLISHED_FEED_META_KEY, QR_SCRIPT_ID, SEED_BROADCAST_CHANNEL, SEED_NAMESPACE, SEED_REGISTERED_WIDGETS, SEED_SCHEMA, SEMVER, SESSION_CSV_HEADER, TELEMETRY_CSV_HEADER, VERSION, applySeedChunk, assertNotebookIndex, assertSeedManifest, assertSeedRow, assertSeedRows, backfillFeedProvenance, buildNoteProvenance, buildStatementTree, canvasRouteSlug, checkUnpublishedFeedChanges, cloneRemoteRecord, composeNoteMarkdown, createIRFile, createUserNotebookLanding, csvToEquipmentLabels, csvToSessionRows, csvToTelemetryBundle, decodeUtf8, effortToMarkdown, emptySeedMeta, encodeUtf8, equipmentToCsv, equipmentToMarkdown, exportPortableFilesFromStorage, extractNoteIdentity, extractTypedTags, feedIdOfMetaKey, getNoteNotebooks, getNotePublicationSummary, ingestPortableFilesIntoStorage, injectIdentityFrontmatter, isIRFile, listScopedPropertyOverrides, makeNotebookLinkId, makeScopedOverrideId, migrateNotebookVocabulary, normalizeFeedTreePath, notebookSlugForChunkId, parseCsvLine, parseFrontmatterDateMs, parseNoteMarkdown, prepareJournalSessionRun, previewRemoteNotebook, previewRemoteRecord, promoteNoteToNotebooks, promoteReferencedOverridesToNotebook, publishFeedFromStorage, qrInlineScript, readFrontmatterMeta, removeNoteFromNotebook, renderFeedLandingHtml, resolveScopedPropertyCatalog, resolveUpstreamProvenance, saveScopedPropertyOverride, seedMetaKey, seedNoteId, seedNoteSourceId, seedPrecedenceRank, seedSourceTier, sessionToCsv, setNoteNotebooks, setNotebookPublic, setSessionPublic, sha256HexAsync, splitCsvRecords, statementToNode, telemetryBundleToCsv } from './chunk-FSWOTQ5M.mjs';
|
|
2
2
|
export * from '@bitcobblers/wod-wiki-core';
|
|
3
|
-
import { dialectRegistry, realtimeProcessorRegistry, summaryProcessorRegistry
|
|
3
|
+
import { dialectRegistry, realtimeProcessorRegistry, summaryProcessorRegistry } from '@bitcobblers/wod-wiki-lang';
|
|
4
4
|
export { ABSENT, AGGREGATE_BUILTINS, AUTHORITATIVE_CASTS, AmrapLogicStrategy, AnalyticsEngine, AnalyticsTransformer, BUILTIN_CALCS, BUNDLED_EFFORT_COUNT, BlockBuilder, BlockContext, ButtonBehavior, CONSUMED_HINTS, CONSUMED_HINT_KEYS, CONTEXT_ATOMS, CalcEngine, CalculationRegistry, CardioDialect, ChildSelectionBehavior, ChildrenStrategy, ChoiceGroupMetric, ClimbDialect, ClimbMetricType, CountdownTimerBehavior, CountupTimerBehavior, CrossFitDialect, DAY, DEFAULT_RESOLVER_OPTIONS, DEFAULT_RUNTIME_OPTIONS, DEFAULT_SOUND_PROFILE, DEFAULT_UNRESOLVED_EFFORT_MET, DIM_LENGTH, DIM_MASS, DIM_TIME, DIM_ZERO, DialectStack, EFFORT_DATA_METRIC_TYPE, EFFORT_REGISTRY_ORIGINS, EffortFallbackStrategy, EffortResolver, ErrorAction, EventBus, ExecutionContext, ExitBehavior, FixtureSyntaxError, GenericGroupStrategy, GenericLoopStrategy, GenericTimerStrategy, HabitsDialect, INTENSITY_TIERS, InMemoryEffortRegistry, IntervalLogicStrategy, JitCompiler, LabelingBehavior, LocalRuntimeSubscription, LookupRegistry, MAX_TAG_CONTRIBUTION_DEPTH, MdTimerRuntime, MemoryLocation, MemoryTypeEnum, NextEvent, OutputEmitter, PRODUCTION_STRATEGIES, PopBlockAction, PushBlockAction, RegisterEventHandlerAction, Registry, ReportOutputBehavior, ReportOutputStrategy, RoundsMetric, RuntimeAdapter, RuntimeClock, RuntimeFactory, RuntimeLogger, RuntimeMemory, RuntimeObservers, RuntimeStack, SEED_PRECEDENCE_RANK, SOUND_PLAY_EVENT, SOUND_PROFILE_METRIC, STORE_CALCS, STREAM_ATOMS, ScriptRuntime, SessionRootStrategy, SnapshotClock, SoundProfileBehavior, SoundStrategy, StandardAnalyticsProfile, StartSessionAction, StartWorkoutAction, SubscriptionManager, TAG_MARKER_PREFIX, TimeSpan, TypedMemoryReference, UNITS, UnitsDialect, UnregisterEventHandlerAction, VISIBILITY_ICONS, VISIBILITY_LABELS, WhiteboardScript, WodDialect, YogaDialect, buildTooltip, bundledEfforts, calculateDuration, calculateElapsed, canonicalizeType, collapseUnresolvedChoices, compareStatement, compileLineForm, compilePropertySummaryCalcs, compoundName, computeColumnLabel, computeLabel, computeWorkloadRollups, createAnalyticsEngineForBlock, createCalcEngine, createCompiler, createDialectStack, createMetricPresentationPolicy, createMockClock, createParser, dailySessionLoads, dayBucket, dedupeEntitiesByPrecedence, dialectRegistry, dialectStack, diffStatement, evaluate, extractMetrics, extractPropertyRulesFromMeta, extractStatements, extractTagPropertyRules, findBestFuzzyMatch, findTagContributionCycles, findUnresolvedChoices, formatDurationCompact, formatDurationSmart, formatSecondsHHMMSS, formatSecondsMMSS, formatSoundTrigger, formatTime, formatTimeHHMMSS, formatTimeMMSS, formatTimePrecise, formatTimestamp, frozenNow, getAnalyticsFromLogs, getAnalyticsFromRuntime, getHints, getMetricVisibility, getRuntimeNowMs, hasHint, hintMetric, hintsToContainer, isCastSubscription, isChoiceResolved, isTimeLikeMetric, isWithinThreshold, levenshteinDistance, metricPresentation, normalizeForFuzzy, outputNodeId, outputNodeIds, parseCalcLine, parseExpression, parseMetricLine, parseScript, parseSoundTrigger, realtimeProcessorRegistry, renderMetric, resolveEntityRank, resolveEntityTier, resolveProfileRules, resolvePropertyDashboardWidgets, resolveSoundProfile, resolveSourceRank, resolveSourceTier, resolveTagContributions, roundToTenth, runMetricShakeOutQueue, strategyRegistry, summaryProcessorRegistry, tagContributionMetrics, tagMarkerSlug, tagMarkerSlugs, tagMarkerType, toStoredOutputStatement, truthy, wallClockNow, whiteboardParser, whiteboardScript, whiteboardScriptLanguage, writeChoiceSelection } from '@bitcobblers/wod-wiki-lang';
|
|
5
|
-
import { WQL_TYPED_TAG_KEYS, notebookSlugFromId, toNotebookId, migrateLegacyChunkId, hasLegacyIdentity, migrateLegacyRow, notebooksOfItem, notebookOfItem, notebookOriginOfItem, notebookSlugOfSourceId } from '@bitcobblers/wod-wiki-wql';
|
|
6
5
|
export { DASHBOARD_GRID_MAX_COLS, DASHBOARD_WIDGET_TYPES, DEFAULT_DASHBOARD_TITLE, DEFAULT_NOTEBOOK_SLUGS, PLANNED_WIDGET_TYPES, QueryService, WQL_AGGREGATORS, WQL_CALC_TARGETS, WQL_CHART_HEADS, WQL_COMPARISON_OPS, WQL_CONTENT_FILTER_KEYS, WQL_DISPLAY_UNITS, WQL_FIND_TARGETS, WQL_FUNCTION_HEADS, WQL_GRAINS, WQL_INTENSITY_TIERS, WQL_KEYWORDS, WQL_METRIC_AGGREGATES, WQL_METRIC_FAMILIES, WQL_RESULT_PLANES, WQL_ROLLUP_PERIODS, WQL_SOURCES, WQL_SOURCE_HEADS, WQL_SOURCE_VALUES, WQL_STANDARD_DATASETS, WQL_TAG_KEYS, WQL_TYPED_TAG_KEYS, WQL_VIRTUAL_DIMS, bindQueryParams, buildDashboardDocument, buildDashboardFromScope, buildDashboardScaffold, buildWidgetsForWqlScope, collectQueryBlockParams, collectQueryParams, dashboardSlug, defaultTokenValues, extractDashboardTokens, extractNoteWqlOverride, isAggregateQuery, isDashboardMeta, isDashboardWidgetType, isDefaultShorthandQueryBlock, isFindQuery, isNoteEditable, isPipelineQuery, isYamlQueryBlockBody, normalizeWql, notebookOfItem, notebookSlugFromId, notebooksOfItem, parseFilterFragment, parseQuery, parseQueryBlock, parseQueryWidgetSuffix, parseWqlSuffixes, queryBlockAttributes, queryBlockToDocumentText, resolveEntityScope, resolveWidgetType, serialize, serializeQueryBlock, serializeQueryBlockFence, splitAtWhere, substituteTokens, toNotebookId, unknownTokensMessage, unknownWidgetTypeMessage, wql, wqlLanguage, wqlParser, wqlTerms } from '@bitcobblers/wod-wiki-wql';
|
|
7
|
-
import { userDeletedSeedNoteId } from '@bitcobblers/wod-wiki-storage';
|
|
8
6
|
|
|
9
|
-
// src/index.ts
|
|
10
7
|
var activePacks = /* @__PURE__ */ new Map();
|
|
11
8
|
function defineLanguagePack(pack) {
|
|
12
9
|
return pack;
|
|
@@ -67,7 +64,7 @@ function inMemoryEventStore(events) {
|
|
|
67
64
|
getEventsByTimeRange: async (start, end) => rows.filter((r) => r.timestamp >= start && r.timestamp <= end),
|
|
68
65
|
getEventsByResult: async (resultId) => rows.filter((r) => r.resultId === resultId),
|
|
69
66
|
getEventsForNote: async (noteId) => rows.filter((r) => r.noteId === noteId),
|
|
70
|
-
getEventsByContent: async (
|
|
67
|
+
getEventsByContent: async (blockContentId) => rows.filter((r) => r.blockContentId === blockContentId),
|
|
71
68
|
scanAll: async () => rows,
|
|
72
69
|
appendEvents: async (appended) => {
|
|
73
70
|
rows.push(...appended);
|
|
@@ -87,4493 +84,7 @@ function inMemoryEventStore(events) {
|
|
|
87
84
|
}
|
|
88
85
|
};
|
|
89
86
|
}
|
|
90
|
-
function createIRFile(kind, data, optionsOrSource, generatedAt) {
|
|
91
|
-
let source = "wod:headless";
|
|
92
|
-
let genAt = Date.now();
|
|
93
|
-
if (typeof optionsOrSource === "string") {
|
|
94
|
-
source = optionsOrSource;
|
|
95
|
-
if (generatedAt !== void 0) genAt = generatedAt;
|
|
96
|
-
} else if (optionsOrSource && typeof optionsOrSource === "object") {
|
|
97
|
-
if (optionsOrSource.source) source = optionsOrSource.source;
|
|
98
|
-
if (optionsOrSource.generatedAt !== void 0) genAt = optionsOrSource.generatedAt;
|
|
99
|
-
}
|
|
100
|
-
return {
|
|
101
|
-
$schema: "https://wod-wiki.dev/ir/v1.json",
|
|
102
|
-
kind,
|
|
103
|
-
generatedAt: genAt,
|
|
104
|
-
source,
|
|
105
|
-
data
|
|
106
|
-
};
|
|
107
|
-
}
|
|
108
|
-
function isIRFile(obj) {
|
|
109
|
-
if (!obj || typeof obj !== "object") return false;
|
|
110
|
-
const cand = obj;
|
|
111
|
-
return cand.$schema === "https://wod-wiki.dev/ir/v1.json" && typeof cand.kind === "string" && typeof cand.generatedAt === "number" && typeof cand.source === "string" && "data" in cand;
|
|
112
|
-
}
|
|
113
|
-
function statementToNode(stmt, idMap) {
|
|
114
|
-
const meta = stmt.meta;
|
|
115
|
-
const metrics = stmt.metrics.toArray().map((m) => ({
|
|
116
|
-
type: m.type,
|
|
117
|
-
...m.image !== void 0 ? { image: m.image } : {},
|
|
118
|
-
...m.value !== void 0 ? { value: m.value } : {},
|
|
119
|
-
...m.origin !== void 0 ? { origin: m.origin } : {}
|
|
120
|
-
}));
|
|
121
|
-
const raw = meta?.raw ?? "";
|
|
122
|
-
const from = meta?.startOffset ?? 0;
|
|
123
|
-
const to = meta?.endOffset ?? from + raw.length;
|
|
124
|
-
const durationFrag = stmt.metrics.find((m) => m.type === MetricType.Duration || m.type === "duration");
|
|
125
|
-
const roundsFrag = stmt.metrics.find((m) => m.type === MetricType.Rounds || m.type === "rounds");
|
|
126
|
-
const type = durationFrag ? "duration" : roundsFrag ? "rounds" : "statement";
|
|
127
|
-
const hints = getHints(stmt);
|
|
128
|
-
const childIds = (stmt.children ?? []).flat();
|
|
129
|
-
const children = childIds.map((cid) => idMap.get(cid)).filter((c) => c !== void 0).map((c) => statementToNode(c, idMap));
|
|
130
|
-
return {
|
|
131
|
-
id: stmt.id,
|
|
132
|
-
type,
|
|
133
|
-
raw,
|
|
134
|
-
from,
|
|
135
|
-
to,
|
|
136
|
-
metrics,
|
|
137
|
-
...hints.length > 0 ? { hints } : {},
|
|
138
|
-
...children.length > 0 ? { children } : {}
|
|
139
|
-
};
|
|
140
|
-
}
|
|
141
|
-
function buildStatementTree(script) {
|
|
142
|
-
const idMap = new Map(script.statements.map((s) => [s.id, s]));
|
|
143
|
-
const topLevel = script.statements.filter((s) => s.parent === void 0 || !idMap.has(s.parent));
|
|
144
|
-
if (topLevel.length === 1 && topLevel[0].children.length > 0) {
|
|
145
|
-
return statementToNode(topLevel[0], idMap);
|
|
146
|
-
}
|
|
147
|
-
return {
|
|
148
|
-
id: 0,
|
|
149
|
-
type: "root",
|
|
150
|
-
raw: script.source,
|
|
151
|
-
from: 0,
|
|
152
|
-
to: script.source.length,
|
|
153
|
-
metrics: [],
|
|
154
|
-
children: topLevel.map((s) => statementToNode(s, idMap))
|
|
155
|
-
};
|
|
156
|
-
}
|
|
157
|
-
var NOTE_ID_FRONTMATTER_KEY = "wod-note-id";
|
|
158
|
-
var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
159
|
-
var NOTEBOOK_LANDING_ID_RE = /^notebook\/[a-z0-9][a-z0-9._-]*$/i;
|
|
160
|
-
function unquoteYamlScalar(raw) {
|
|
161
|
-
const trimmed = raw.trim();
|
|
162
|
-
if (trimmed.startsWith('"') && trimmed.endsWith('"') || trimmed.startsWith("'") && trimmed.endsWith("'")) {
|
|
163
|
-
try {
|
|
164
|
-
if (trimmed.startsWith('"')) return JSON.parse(trimmed);
|
|
165
|
-
} catch {
|
|
166
|
-
}
|
|
167
|
-
return trimmed.slice(1, -1);
|
|
168
|
-
}
|
|
169
|
-
return trimmed;
|
|
170
|
-
}
|
|
171
|
-
function extractNoteIdentity(markdown) {
|
|
172
|
-
const block = /^---\r?\n([\s\S]*?)\r?\n---/.exec(markdown);
|
|
173
|
-
if (!block) return void 0;
|
|
174
|
-
let noteId;
|
|
175
|
-
let title;
|
|
176
|
-
let date;
|
|
177
|
-
let notebook;
|
|
178
|
-
let isPublic;
|
|
179
|
-
for (const line of block[1].split(/\r?\n/)) {
|
|
180
|
-
const kv = line.match(/^([^:]+):\s*(.*)$/);
|
|
181
|
-
if (!kv) continue;
|
|
182
|
-
const key = kv[1].trim();
|
|
183
|
-
const value = unquoteYamlScalar(kv[2]);
|
|
184
|
-
if (key === NOTE_ID_FRONTMATTER_KEY && (UUID_RE.test(value) || NOTEBOOK_LANDING_ID_RE.test(value))) {
|
|
185
|
-
noteId = value;
|
|
186
|
-
}
|
|
187
|
-
if (key === "title" && value) title = value;
|
|
188
|
-
if (key === "date" && value) date = value;
|
|
189
|
-
if (key === "notebook" && value) notebook = value;
|
|
190
|
-
if (key === "public" && (value === "true" || value === "false")) isPublic = value === "true";
|
|
191
|
-
}
|
|
192
|
-
if (!noteId) return void 0;
|
|
193
|
-
return {
|
|
194
|
-
noteId,
|
|
195
|
-
...title !== void 0 ? { title } : {},
|
|
196
|
-
...date !== void 0 ? { date } : {},
|
|
197
|
-
...notebook !== void 0 ? { notebook } : {},
|
|
198
|
-
...isPublic !== void 0 ? { public: isPublic } : {}
|
|
199
|
-
};
|
|
200
|
-
}
|
|
201
|
-
var FRONTMATTER_SAFE = /^[^:#\[\]{}'"*&,!?|>%@`\s][^:#\[\]{}"']*$/;
|
|
202
|
-
function formatFrontmatterScalar(value) {
|
|
203
|
-
if (FRONTMATTER_SAFE.test(value)) return value;
|
|
204
|
-
if (!value.includes("\n") && !value.includes("\r")) return JSON.stringify(value);
|
|
205
|
-
return void 0;
|
|
206
|
-
}
|
|
207
|
-
function parseFrontmatterDateMs(raw) {
|
|
208
|
-
if (!raw) return void 0;
|
|
209
|
-
const clean = unquoteYamlScalar(raw);
|
|
210
|
-
const ymd = clean.match(/^(\d{4})-(\d{2})-(\d{2})$/);
|
|
211
|
-
if (ymd) {
|
|
212
|
-
const ts = Date.parse(`${clean}T12:00:00Z`);
|
|
213
|
-
const d = new Date(ts);
|
|
214
|
-
if (Number.isFinite(ts) && d.getUTCMonth() === Number(ymd[2]) - 1 && d.getUTCDate() === Number(ymd[3])) {
|
|
215
|
-
return ts;
|
|
216
|
-
}
|
|
217
|
-
return void 0;
|
|
218
|
-
}
|
|
219
|
-
const parsed = Date.parse(clean);
|
|
220
|
-
return Number.isFinite(parsed) ? parsed : void 0;
|
|
221
|
-
}
|
|
222
|
-
function injectIdentityFrontmatter(markdown, identity) {
|
|
223
|
-
const stamp = (lines2) => {
|
|
224
|
-
const replaceOrInsert = (key, value) => {
|
|
225
|
-
if (value === void 0) return;
|
|
226
|
-
const formatted = formatFrontmatterScalar(value);
|
|
227
|
-
if (formatted === void 0) return;
|
|
228
|
-
const idx = lines2.findIndex((l) => l.startsWith(`${key}:`));
|
|
229
|
-
if (idx >= 0) lines2[idx] = `${key}: ${formatted}`;
|
|
230
|
-
else lines2.push(`${key}: ${formatted}`);
|
|
231
|
-
};
|
|
232
|
-
replaceOrInsert("title", identity.title);
|
|
233
|
-
replaceOrInsert(NOTE_ID_FRONTMATTER_KEY, identity.noteId);
|
|
234
|
-
replaceOrInsert("date", identity.date);
|
|
235
|
-
replaceOrInsert("notebook", identity.notebook);
|
|
236
|
-
if (identity.public !== void 0) {
|
|
237
|
-
replaceOrInsert("public", identity.public ? "true" : "false");
|
|
238
|
-
}
|
|
239
|
-
return lines2;
|
|
240
|
-
};
|
|
241
|
-
const block = /^---\r?\n([\s\S]*?)\r?\n---/.exec(markdown);
|
|
242
|
-
if (block) {
|
|
243
|
-
const newline = markdown.startsWith("---\r\n") ? "\r\n" : "\n";
|
|
244
|
-
const lines2 = stamp(block[1].split(/\r?\n/));
|
|
245
|
-
return `---${newline}${lines2.join(newline)}${newline}---${markdown.slice(block[0].length)}`;
|
|
246
|
-
}
|
|
247
|
-
const lines = stamp([]);
|
|
248
|
-
return `---
|
|
249
|
-
${lines.join("\n")}
|
|
250
|
-
---
|
|
251
|
-
|
|
252
|
-
${markdown}`;
|
|
253
|
-
}
|
|
254
|
-
function composeNoteMarkdown(note) {
|
|
255
|
-
const notebookSlug = note.notebookId ? notebookSlugFromId(note.notebookId) : void 0;
|
|
256
|
-
const dateStr = typeof note.date === "number" && Number.isFinite(note.date) ? new Date(note.date).toISOString().slice(0, 10) : void 0;
|
|
257
|
-
return injectIdentityFrontmatter(note.rawContent, {
|
|
258
|
-
noteId: note.id,
|
|
259
|
-
title: note.title,
|
|
260
|
-
...dateStr ? { date: dateStr } : {},
|
|
261
|
-
...notebookSlug ? { notebook: notebookSlug } : {},
|
|
262
|
-
...note.public === true ? { public: true } : {}
|
|
263
|
-
});
|
|
264
|
-
}
|
|
265
|
-
function parseNoteMarkdown(markdown, options = {}) {
|
|
266
|
-
const identity = extractNoteIdentity(markdown);
|
|
267
|
-
const meta = readFrontmatterMeta(markdown);
|
|
268
|
-
const typedTags = extractTypedTags(markdown);
|
|
269
|
-
let rawContent = markdown;
|
|
270
|
-
const fmMatch = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n)?(?:\r?\n)?/.exec(markdown);
|
|
271
|
-
if (fmMatch) {
|
|
272
|
-
const fmLines = fmMatch[1].split(/\r?\n/);
|
|
273
|
-
const nonIdentityLines = fmLines.filter((line) => {
|
|
274
|
-
const kv = line.match(/^([^:]+):/);
|
|
275
|
-
if (!kv) return true;
|
|
276
|
-
const k = kv[1].trim().toLowerCase();
|
|
277
|
-
return k !== NOTE_ID_FRONTMATTER_KEY;
|
|
278
|
-
});
|
|
279
|
-
const onlyTitleLeft = nonIdentityLines.length === 1 && nonIdentityLines[0].trim().toLowerCase().startsWith("title:");
|
|
280
|
-
const body = markdown.slice(fmMatch[0].length);
|
|
281
|
-
if (nonIdentityLines.length === 0 || onlyTitleLeft && /^#\s+.+/m.test(body)) {
|
|
282
|
-
rawContent = body;
|
|
283
|
-
} else if (nonIdentityLines.length !== fmLines.length) {
|
|
284
|
-
const nl = markdown.startsWith("---\r\n") ? "\r\n" : "\n";
|
|
285
|
-
const rest = markdown.slice(
|
|
286
|
-
/^---\r?\n[\s\S]*?\r?\n---/.exec(markdown)?.[0].length ?? fmMatch[0].length
|
|
287
|
-
);
|
|
288
|
-
rawContent = `---${nl}${nonIdentityLines.join(nl)}${nl}---${rest}`;
|
|
289
|
-
}
|
|
290
|
-
}
|
|
291
|
-
const headingMatch = rawContent.match(/^#\s+(.+)$/m) ?? markdown.match(/^#\s+(.+)$/m);
|
|
292
|
-
const metaTitle = typeof meta["title"] === "string" ? unquoteYamlScalar(meta["title"]) : void 0;
|
|
293
|
-
const title = identity?.title ?? metaTitle ?? (headingMatch ? headingMatch[1].trim() : void 0) ?? options.fallbackTitle ?? "Imported Note";
|
|
294
|
-
const rawDate = identity?.date ?? (typeof meta["date"] === "string" ? meta["date"] : void 0);
|
|
295
|
-
const date = parseFrontmatterDateMs(rawDate) ?? options.defaultDate;
|
|
296
|
-
const rawNotebook = identity?.notebook ?? (typeof meta["notebook"] === "string" ? unquoteYamlScalar(meta["notebook"]) : void 0);
|
|
297
|
-
const notebookId = rawNotebook ? toNotebookId(rawNotebook) : void 0;
|
|
298
|
-
const rawPublic = meta["public"];
|
|
299
|
-
const isPublic = identity?.public ?? (typeof rawPublic === "string" && (rawPublic === "true" || rawPublic === "false") ? rawPublic === "true" : void 0);
|
|
300
|
-
const sourceRevision = options.sourceRevision ?? 1;
|
|
301
|
-
const blocks = reconcileNoteBlocks(rawContent, {
|
|
302
|
-
sourceRevision,
|
|
303
|
-
registeredWidgets: KNOWN_SECTION_WIDGETS
|
|
304
|
-
});
|
|
305
|
-
return {
|
|
306
|
-
...identity?.noteId ? { id: identity.noteId } : {},
|
|
307
|
-
title,
|
|
308
|
-
rawContent,
|
|
309
|
-
...date !== void 0 ? { date } : {},
|
|
310
|
-
...notebookId ? { notebookId } : {},
|
|
311
|
-
...isPublic !== void 0 ? { public: isPublic } : {},
|
|
312
|
-
tags: asList(meta["tags"]),
|
|
313
|
-
typedTags,
|
|
314
|
-
blocks
|
|
315
|
-
};
|
|
316
|
-
}
|
|
317
|
-
var FRONTMATTER_BLOCK_RE = /^---\r?\n([\s\S]*?)\r?\n---/;
|
|
318
|
-
function readFrontmatterMeta(markdown) {
|
|
319
|
-
const match = FRONTMATTER_BLOCK_RE.exec(markdown);
|
|
320
|
-
if (!match) return {};
|
|
321
|
-
const meta = {};
|
|
322
|
-
const lines = match[1].split(/\r?\n/);
|
|
323
|
-
let currentListKey;
|
|
324
|
-
for (const rawLine of lines) {
|
|
325
|
-
const line = rawLine.trimEnd();
|
|
326
|
-
const item = line.match(/^\s+-\s+(.*)$/);
|
|
327
|
-
if (item && currentListKey) {
|
|
328
|
-
meta[currentListKey].push(item[1].trim());
|
|
329
|
-
continue;
|
|
330
|
-
}
|
|
331
|
-
const kv = line.match(/^([^:]+):\s*(.*)$/);
|
|
332
|
-
if (!kv) continue;
|
|
333
|
-
const key = kv[1].trim().toLowerCase();
|
|
334
|
-
const value = kv[2].trim();
|
|
335
|
-
if (value === "") {
|
|
336
|
-
meta[key] = [];
|
|
337
|
-
currentListKey = key;
|
|
338
|
-
} else if (value.startsWith("[") && value.endsWith("]")) {
|
|
339
|
-
meta[key] = value.slice(1, -1).split(",").map((v) => v.trim().replace(/^['"]|['"]$/g, "")).filter((v) => v.length > 0);
|
|
340
|
-
currentListKey = void 0;
|
|
341
|
-
} else {
|
|
342
|
-
meta[key] = value;
|
|
343
|
-
currentListKey = void 0;
|
|
344
|
-
}
|
|
345
|
-
}
|
|
346
|
-
return meta;
|
|
347
|
-
}
|
|
348
|
-
var asList = (value) => Array.isArray(value) ? value : typeof value === "string" ? value.split(",").map((v) => v.trim()).filter((v) => v.length > 0) : [];
|
|
349
|
-
function extractTypedTags(markdown, typedKeys = WQL_TYPED_TAG_KEYS) {
|
|
350
|
-
const meta = readFrontmatterMeta(markdown);
|
|
351
|
-
const results = asList(meta["tags"]).map((label) => ({ label }));
|
|
352
|
-
const metaKeys = Object.keys(meta);
|
|
353
|
-
for (const typeName of typedKeys) {
|
|
354
|
-
if (typeName === "tags") continue;
|
|
355
|
-
const matchedKey = metaKeys.find((k) => k === typeName.toLowerCase());
|
|
356
|
-
if (!matchedKey) continue;
|
|
357
|
-
for (const label of asList(meta[matchedKey])) {
|
|
358
|
-
results.push({ label, type: typeName });
|
|
359
|
-
}
|
|
360
|
-
}
|
|
361
|
-
return results.filter((t) => t.label.length > 0);
|
|
362
|
-
}
|
|
363
|
-
function effortToMarkdown(effort) {
|
|
364
|
-
const lines = ["---", `id: ${effort.id}`, `slug: ${effort.slug}`, `label: ${effort.label}`];
|
|
365
|
-
if (effort.aliases && effort.aliases.length > 0) {
|
|
366
|
-
lines.push("aliases:");
|
|
367
|
-
for (const alias of effort.aliases) lines.push(` - ${alias}`);
|
|
368
|
-
}
|
|
369
|
-
const attrs = Object.entries(effort.baseAttributes).filter(([, v]) => typeof v === "number" || typeof v === "string");
|
|
370
|
-
if (attrs.length > 0) {
|
|
371
|
-
lines.push("baseAttributes:");
|
|
372
|
-
for (const [k, v] of attrs) lines.push(` ${k}: ${String(v)}`);
|
|
373
|
-
}
|
|
374
|
-
lines.push("---", "");
|
|
375
|
-
return `${lines.join("\n")}
|
|
376
|
-
${(effort.body ?? "").trim()}`.trimEnd() + "\n";
|
|
377
|
-
}
|
|
378
|
-
function equipmentToMarkdown(equipment) {
|
|
379
|
-
const lines = ["---", "type: equipment", `id: ${equipment.id}`, `slug: ${equipment.slug}`, `label: ${equipment.label}`];
|
|
380
|
-
if (equipment.aliases && equipment.aliases.length > 0) {
|
|
381
|
-
lines.push("aliases:");
|
|
382
|
-
for (const alias of equipment.aliases) lines.push(` - ${alias}`);
|
|
383
|
-
}
|
|
384
|
-
lines.push("---", "");
|
|
385
|
-
return `${lines.join("\n")}
|
|
386
|
-
${(equipment.body ?? "").trim()}`.trimEnd() + "\n";
|
|
387
|
-
}
|
|
388
|
-
function equipmentToCsv(labels) {
|
|
389
|
-
return ["label", ...labels].map((l) => escapeCsvField(l)).join("\n") + "\n";
|
|
390
|
-
}
|
|
391
|
-
function csvToEquipmentLabels(csv) {
|
|
392
|
-
const lines = splitCsvRecords(csv);
|
|
393
|
-
if (lines.length === 0) return [];
|
|
394
|
-
const header = parseCsvLine(lines[0]);
|
|
395
|
-
const labelIdx = header[0] === "label" ? 0 : -1;
|
|
396
|
-
const start = labelIdx >= 0 ? 1 : 0;
|
|
397
|
-
const labels = [];
|
|
398
|
-
for (const line of lines.slice(start)) {
|
|
399
|
-
const cells = parseCsvLine(line);
|
|
400
|
-
const label = (labelIdx >= 0 ? cells[0] : cells.join(",")).trim();
|
|
401
|
-
if (label) labels.push(label);
|
|
402
|
-
}
|
|
403
|
-
return [...new Set(labels)];
|
|
404
|
-
}
|
|
405
|
-
var SESSION_HEADER = [
|
|
406
|
-
"sessionId",
|
|
407
|
-
"noteId",
|
|
408
|
-
"blockId",
|
|
409
|
-
"blockVersion",
|
|
410
|
-
"blockContentId",
|
|
411
|
-
"origin",
|
|
412
|
-
"status",
|
|
413
|
-
"startTime",
|
|
414
|
-
"endTime",
|
|
415
|
-
"duration",
|
|
416
|
-
"completed",
|
|
417
|
-
"sessionCreatedAt",
|
|
418
|
-
"sessionExtraJson"
|
|
419
|
-
];
|
|
420
|
-
var EVENT_HEADER = [
|
|
421
|
-
"eventId",
|
|
422
|
-
"grain",
|
|
423
|
-
"outputType",
|
|
424
|
-
"timestamp",
|
|
425
|
-
"pageId",
|
|
426
|
-
"effortSlug",
|
|
427
|
-
"eventBlockId",
|
|
428
|
-
"eventBlockVersion",
|
|
429
|
-
"eventBlockContentId",
|
|
430
|
-
"eventOrigin",
|
|
431
|
-
"timeSpan",
|
|
432
|
-
"sourceBlockKey",
|
|
433
|
-
"sourceStatementId",
|
|
434
|
-
"line",
|
|
435
|
-
"text",
|
|
436
|
-
"dialect",
|
|
437
|
-
"stackLevel",
|
|
438
|
-
"completionReason",
|
|
439
|
-
"representationKind",
|
|
440
|
-
"metricType",
|
|
441
|
-
"metricValue",
|
|
442
|
-
"metricUnit",
|
|
443
|
-
"metricImage",
|
|
444
|
-
"metricOrigin",
|
|
445
|
-
"metricMetadata",
|
|
446
|
-
"metricTemporal",
|
|
447
|
-
// Verbatim JSON backstops: make the machine round-trip lossless across
|
|
448
|
-
// schema fields that have no dedicated spreadsheet column. Explicit cells
|
|
449
|
-
// above still win on import, so hand-edited values are honored.
|
|
450
|
-
"metricJson",
|
|
451
|
-
"eventExtraJson"
|
|
452
|
-
];
|
|
453
|
-
var SESSION_CSV_HEADER = [...SESSION_HEADER, ...EVENT_HEADER];
|
|
454
|
-
function escapeCsvField(field) {
|
|
455
|
-
if (field === void 0 || field === null) return "";
|
|
456
|
-
const str = typeof field === "object" ? JSON.stringify(field) : String(field);
|
|
457
|
-
if (str.includes(",") || str.includes('"') || str.includes("\n") || str.includes("\r")) {
|
|
458
|
-
return `"${str.replace(/"/g, '""')}"`;
|
|
459
|
-
}
|
|
460
|
-
return str;
|
|
461
|
-
}
|
|
462
|
-
var metricValueToCell = (value) => {
|
|
463
|
-
if (value === void 0 || value === null) return "";
|
|
464
|
-
if (typeof value === "object") return JSON.stringify(value);
|
|
465
|
-
return String(value);
|
|
466
|
-
};
|
|
467
|
-
var metricValueFromCell = (cell) => {
|
|
468
|
-
if (cell === "") return void 0;
|
|
469
|
-
if (/^-?\d+(\.\d+)?$/.test(cell)) return Number(cell);
|
|
470
|
-
if (cell === "true" || cell === "false") return cell === "true";
|
|
471
|
-
if (cell.startsWith("{") || cell.startsWith("[")) {
|
|
472
|
-
try {
|
|
473
|
-
return JSON.parse(cell);
|
|
474
|
-
} catch {
|
|
475
|
-
return cell;
|
|
476
|
-
}
|
|
477
|
-
}
|
|
478
|
-
return cell;
|
|
479
|
-
};
|
|
480
|
-
function sessionCells(session) {
|
|
481
|
-
return [
|
|
482
|
-
session.id,
|
|
483
|
-
session.noteId,
|
|
484
|
-
session.blockId,
|
|
485
|
-
session.blockVersion,
|
|
486
|
-
session.blockContentId,
|
|
487
|
-
session.origin,
|
|
488
|
-
session.status,
|
|
489
|
-
session.startTime,
|
|
490
|
-
session.endTime,
|
|
491
|
-
session.duration,
|
|
492
|
-
session.completed,
|
|
493
|
-
session.createdAt,
|
|
494
|
-
JSON.stringify(session)
|
|
495
|
-
].map(escapeCsvField);
|
|
496
|
-
}
|
|
497
|
-
function metricCells(event, metric, index) {
|
|
498
|
-
return [
|
|
499
|
-
event.id,
|
|
500
|
-
event.grain,
|
|
501
|
-
event.outputType,
|
|
502
|
-
event.timestamp,
|
|
503
|
-
event.pageId,
|
|
504
|
-
event.effortSlug,
|
|
505
|
-
event.blockId,
|
|
506
|
-
event.blockVersion,
|
|
507
|
-
event.blockContentId,
|
|
508
|
-
event.origin,
|
|
509
|
-
event.timeSpan,
|
|
510
|
-
event.sourceBlockKey,
|
|
511
|
-
event.sourceStatementId,
|
|
512
|
-
event.line,
|
|
513
|
-
event.text,
|
|
514
|
-
event.dialect,
|
|
515
|
-
event.stackLevel,
|
|
516
|
-
event.completionReason,
|
|
517
|
-
event.representationKind,
|
|
518
|
-
metric.type,
|
|
519
|
-
metricValueToCell(metric.value),
|
|
520
|
-
metric.unit,
|
|
521
|
-
metric.image,
|
|
522
|
-
metric.origin,
|
|
523
|
-
metric.metadata === void 0 ? "" : JSON.stringify(metric.metadata),
|
|
524
|
-
event.metricTemporal?.[index] === void 0 ? "" : JSON.stringify(event.metricTemporal[index]),
|
|
525
|
-
JSON.stringify(metric)
|
|
526
|
-
].map(escapeCsvField);
|
|
527
|
-
}
|
|
528
|
-
function eventExtraCells(event) {
|
|
529
|
-
const { metrics: _metrics, ...rest } = event;
|
|
530
|
-
return escapeCsvField(JSON.stringify(rest));
|
|
531
|
-
}
|
|
532
|
-
function sessionToCsv(session, events) {
|
|
533
|
-
const lines = [SESSION_CSV_HEADER.join(",")];
|
|
534
|
-
lines.push([...sessionCells(session), ...EVENT_HEADER.map(() => "")].join(","));
|
|
535
|
-
const ordered = [...events].sort((a, b) => a.id.localeCompare(b.id));
|
|
536
|
-
for (const event of ordered) {
|
|
537
|
-
const extra = eventExtraCells(event);
|
|
538
|
-
const metrics = event.metrics ?? [];
|
|
539
|
-
if (metrics.length === 0) {
|
|
540
|
-
lines.push([...sessionCells(session), ...metricCells(event, { type: "" }, 0), extra].join(","));
|
|
541
|
-
continue;
|
|
542
|
-
}
|
|
543
|
-
for (let i = 0; i < metrics.length; i++) {
|
|
544
|
-
lines.push([...sessionCells(session), ...metricCells(event, metrics[i], i), extra].join(","));
|
|
545
|
-
}
|
|
546
|
-
}
|
|
547
|
-
return lines.join("\n") + "\n";
|
|
548
|
-
}
|
|
549
|
-
function parseCsvLine(line) {
|
|
550
|
-
const cells = [];
|
|
551
|
-
let current = "";
|
|
552
|
-
let quoted = false;
|
|
553
|
-
for (let i = 0; i < line.length; i++) {
|
|
554
|
-
const ch = line[i];
|
|
555
|
-
if (quoted) {
|
|
556
|
-
if (ch === '"') {
|
|
557
|
-
if (line[i + 1] === '"') {
|
|
558
|
-
current += '"';
|
|
559
|
-
i += 1;
|
|
560
|
-
} else {
|
|
561
|
-
quoted = false;
|
|
562
|
-
}
|
|
563
|
-
} else {
|
|
564
|
-
current += ch;
|
|
565
|
-
}
|
|
566
|
-
} else if (ch === '"' && current === "") {
|
|
567
|
-
quoted = true;
|
|
568
|
-
} else if (ch === ",") {
|
|
569
|
-
cells.push(current);
|
|
570
|
-
current = "";
|
|
571
|
-
} else {
|
|
572
|
-
current += ch;
|
|
573
|
-
}
|
|
574
|
-
}
|
|
575
|
-
cells.push(current);
|
|
576
|
-
return cells;
|
|
577
|
-
}
|
|
578
|
-
function splitCsvRecords(csv) {
|
|
579
|
-
const records = [];
|
|
580
|
-
let current = "";
|
|
581
|
-
let quoted = false;
|
|
582
|
-
for (let i = 0; i < csv.length; i++) {
|
|
583
|
-
const ch = csv[i];
|
|
584
|
-
if (ch === '"') {
|
|
585
|
-
if (quoted && csv[i + 1] === '"') {
|
|
586
|
-
current += '""';
|
|
587
|
-
i += 1;
|
|
588
|
-
continue;
|
|
589
|
-
}
|
|
590
|
-
quoted = !quoted;
|
|
591
|
-
current += ch;
|
|
592
|
-
} else if (!quoted && (ch === "\n" || ch === "\r")) {
|
|
593
|
-
if (ch === "\r" && csv[i + 1] === "\n") i += 1;
|
|
594
|
-
if (current.length > 0) records.push(current);
|
|
595
|
-
current = "";
|
|
596
|
-
} else {
|
|
597
|
-
current += ch;
|
|
598
|
-
}
|
|
599
|
-
}
|
|
600
|
-
if (current.length > 0) records.push(current);
|
|
601
|
-
return records;
|
|
602
|
-
}
|
|
603
|
-
var num = (cell) => cell === "" ? void 0 : Number(cell);
|
|
604
|
-
var nonempty = (cell) => cell === "" ? void 0 : cell;
|
|
605
|
-
function jsonCell(cell) {
|
|
606
|
-
if (!cell) return void 0;
|
|
607
|
-
try {
|
|
608
|
-
return JSON.parse(cell);
|
|
609
|
-
} catch {
|
|
610
|
-
return void 0;
|
|
611
|
-
}
|
|
612
|
-
}
|
|
613
|
-
function csvToSessionRows(csv) {
|
|
614
|
-
const lines = splitCsvRecords(csv);
|
|
615
|
-
if (lines.length < 2) throw new Error("[wod import] Session CSV has no data rows");
|
|
616
|
-
const header = parseCsvLine(lines[0]);
|
|
617
|
-
if (header.some((name) => /segment/i.test(name))) {
|
|
618
|
-
throw new Error("[wod import] Incompatible Session CSV segment pins; blockId/blockVersion are required");
|
|
619
|
-
}
|
|
620
|
-
const col = (name) => {
|
|
621
|
-
const idx = header.indexOf(name);
|
|
622
|
-
if (idx < 0) throw new Error(`[wod import] Session CSV missing column "${name}"`);
|
|
623
|
-
return idx;
|
|
624
|
-
};
|
|
625
|
-
const at = (cells, name) => cells[col(name)] ?? "";
|
|
626
|
-
const eventRows = /* @__PURE__ */ new Map();
|
|
627
|
-
let session;
|
|
628
|
-
const ensureSession = (cells) => {
|
|
629
|
-
const id = at(cells, "sessionId");
|
|
630
|
-
const noteId = at(cells, "noteId");
|
|
631
|
-
const blockId = at(cells, "blockId");
|
|
632
|
-
const blockVersion = Number(at(cells, "blockVersion"));
|
|
633
|
-
if (!id || !noteId || !blockId || !Number.isSafeInteger(blockVersion) || blockVersion < 1) {
|
|
634
|
-
throw new Error("[wod import] Session CSV requires sessionId, noteId, blockId and positive blockVersion");
|
|
635
|
-
}
|
|
636
|
-
if (session) {
|
|
637
|
-
if (session.id !== id || session.noteId !== noteId || session.blockId !== blockId || session.blockVersion !== blockVersion) {
|
|
638
|
-
throw new Error("[wod import] Session CSV contains inconsistent source pins");
|
|
639
|
-
}
|
|
640
|
-
return session;
|
|
641
|
-
}
|
|
642
|
-
const extra = jsonCell(at(cells, "sessionExtraJson")) ?? {};
|
|
643
|
-
if ("segmentId" in extra || "segmentVersion" in extra || "version" in extra || "rawContent" in extra || "data" in extra) {
|
|
644
|
-
throw new Error("[wod import] Incompatible Session CSV source snapshot or segment pin");
|
|
645
|
-
}
|
|
646
|
-
session = {
|
|
647
|
-
...extra,
|
|
648
|
-
id,
|
|
649
|
-
noteId,
|
|
650
|
-
blockId,
|
|
651
|
-
blockVersion,
|
|
652
|
-
blockContentId: at(cells, "blockContentId") || void 0,
|
|
653
|
-
origin: at(cells, "origin") || void 0,
|
|
654
|
-
status: at(cells, "status") || void 0,
|
|
655
|
-
startTime: Number(at(cells, "startTime") || 0),
|
|
656
|
-
endTime: Number(at(cells, "endTime") || 0),
|
|
657
|
-
duration: Number(at(cells, "duration") || 0),
|
|
658
|
-
completed: at(cells, "completed") === "true",
|
|
659
|
-
createdAt: Number(at(cells, "sessionCreatedAt") || 0)
|
|
660
|
-
};
|
|
661
|
-
if (![session.startTime, session.endTime, session.duration, session.createdAt].every(Number.isFinite)) {
|
|
662
|
-
throw new Error("[wod import] Session CSV lifecycle values must be finite numbers");
|
|
663
|
-
}
|
|
664
|
-
return session;
|
|
665
|
-
};
|
|
666
|
-
for (const line of lines.slice(1)) {
|
|
667
|
-
const cells = parseCsvLine(line);
|
|
668
|
-
if (cells.length === 1 && cells[0] === "") continue;
|
|
669
|
-
const currentSession = ensureSession(cells);
|
|
670
|
-
const eventId = at(cells, "eventId");
|
|
671
|
-
if (!eventId) continue;
|
|
672
|
-
let event = eventRows.get(eventId);
|
|
673
|
-
if (!event) {
|
|
674
|
-
const extra = jsonCell(at(cells, "eventExtraJson")) ?? {};
|
|
675
|
-
if ("segmentId" in extra || "segmentVersion" in extra) {
|
|
676
|
-
throw new Error("[wod import] Incompatible Session CSV event segment pins");
|
|
677
|
-
}
|
|
678
|
-
const blockId = nonempty(at(cells, "eventBlockId"));
|
|
679
|
-
const blockVersion = num(at(cells, "eventBlockVersion"));
|
|
680
|
-
if (blockId !== currentSession.blockId || blockVersion !== currentSession.blockVersion) {
|
|
681
|
-
throw new Error("[wod import] Event source pin differs from Session source pin");
|
|
682
|
-
}
|
|
683
|
-
event = {
|
|
684
|
-
...extra,
|
|
685
|
-
id: eventId,
|
|
686
|
-
resultId: currentSession.id,
|
|
687
|
-
noteId: nonempty(at(cells, "noteId")) ?? extra.noteId ?? currentSession.noteId,
|
|
688
|
-
blockContentId: nonempty(at(cells, "eventBlockContentId")) ?? extra.blockContentId,
|
|
689
|
-
pageId: nonempty(at(cells, "pageId")) ?? extra.pageId,
|
|
690
|
-
origin: nonempty(at(cells, "eventOrigin")) ?? extra.origin,
|
|
691
|
-
timestamp: Number(at(cells, "timestamp") || extra.timestamp || 0),
|
|
692
|
-
grain: nonempty(at(cells, "grain")) ?? extra.grain ?? "event",
|
|
693
|
-
effortSlug: nonempty(at(cells, "effortSlug")) ?? extra.effortSlug,
|
|
694
|
-
outputType: nonempty(at(cells, "outputType")) ?? extra.outputType ?? "event",
|
|
695
|
-
blockId,
|
|
696
|
-
blockVersion,
|
|
697
|
-
timeSpan: jsonCell(at(cells, "timeSpan")) ?? extra.timeSpan,
|
|
698
|
-
sourceBlockKey: nonempty(at(cells, "sourceBlockKey")) ?? extra.sourceBlockKey,
|
|
699
|
-
sourceStatementId: num(at(cells, "sourceStatementId")) ?? extra.sourceStatementId,
|
|
700
|
-
line: num(at(cells, "line")) ?? extra.line,
|
|
701
|
-
text: nonempty(at(cells, "text")) ?? extra.text,
|
|
702
|
-
dialect: nonempty(at(cells, "dialect")) ?? extra.dialect,
|
|
703
|
-
stackLevel: num(at(cells, "stackLevel")) ?? extra.stackLevel,
|
|
704
|
-
completionReason: nonempty(at(cells, "completionReason")) ?? extra.completionReason,
|
|
705
|
-
representationKind: nonempty(at(cells, "representationKind")) ?? extra.representationKind,
|
|
706
|
-
metrics: [],
|
|
707
|
-
// Rebuild anchors from metric rows while preserving an authored empty array.
|
|
708
|
-
metricTemporal: Array.isArray(extra.metricTemporal) ? [] : void 0
|
|
709
|
-
};
|
|
710
|
-
eventRows.set(eventId, event);
|
|
711
|
-
}
|
|
712
|
-
const metricType = at(cells, "metricType");
|
|
713
|
-
if (!metricType) continue;
|
|
714
|
-
const baseMetric = jsonCell(at(cells, "metricJson")) ?? {};
|
|
715
|
-
const metric = {
|
|
716
|
-
...baseMetric,
|
|
717
|
-
type: metricType,
|
|
718
|
-
...at(cells, "metricValue") !== "" ? { value: metricValueFromCell(at(cells, "metricValue")) } : {},
|
|
719
|
-
...nonempty(at(cells, "metricUnit")) ? { unit: at(cells, "metricUnit") } : {},
|
|
720
|
-
...nonempty(at(cells, "metricImage")) ? { image: at(cells, "metricImage") } : {},
|
|
721
|
-
...nonempty(at(cells, "metricOrigin")) ? { origin: at(cells, "metricOrigin") } : {},
|
|
722
|
-
...at(cells, "metricMetadata") !== "" ? { metadata: jsonCell(at(cells, "metricMetadata")) } : {}
|
|
723
|
-
};
|
|
724
|
-
event.metrics.push(metric);
|
|
725
|
-
const temporal = jsonCell(at(cells, "metricTemporal"));
|
|
726
|
-
if (temporal !== void 0) {
|
|
727
|
-
(event.metricTemporal ??= []).push(temporal);
|
|
728
|
-
}
|
|
729
|
-
}
|
|
730
|
-
if (!session) throw new Error("[wod import] Session CSV did not contain session columns");
|
|
731
|
-
return { session, events: [...eventRows.values()] };
|
|
732
|
-
}
|
|
733
|
-
var TELEMETRY_EXTRA_COLS = [
|
|
734
|
-
"revisionKind",
|
|
735
|
-
"revisionRawContent",
|
|
736
|
-
"revisionSavedAt",
|
|
737
|
-
"revisionDialect",
|
|
738
|
-
"revisionSport",
|
|
739
|
-
"parseId",
|
|
740
|
-
"parseStage",
|
|
741
|
-
"parseStatus",
|
|
742
|
-
"parseDiagnosticsJson",
|
|
743
|
-
"parseMetricsJson"
|
|
744
|
-
];
|
|
745
|
-
var TELEMETRY_CSV_HEADER = [
|
|
746
|
-
"recordKind",
|
|
747
|
-
...SESSION_CSV_HEADER,
|
|
748
|
-
...TELEMETRY_EXTRA_COLS
|
|
749
|
-
];
|
|
750
|
-
function telemetryBundleToCsv(bundle) {
|
|
751
|
-
const lines = [TELEMETRY_CSV_HEADER.join(",")];
|
|
752
|
-
for (const rev of bundle.revisions ?? []) {
|
|
753
|
-
const sessionCols = new Array(SESSION_HEADER.length).fill("");
|
|
754
|
-
sessionCols[1] = escapeCsvField(rev.noteId);
|
|
755
|
-
sessionCols[2] = escapeCsvField(rev.blockId);
|
|
756
|
-
sessionCols[3] = escapeCsvField(rev.version);
|
|
757
|
-
const eventCols = new Array(EVENT_HEADER.length).fill("");
|
|
758
|
-
const extraCols = [
|
|
759
|
-
escapeCsvField(rev.kind),
|
|
760
|
-
escapeCsvField(rev.rawContent),
|
|
761
|
-
escapeCsvField(rev.savedAt),
|
|
762
|
-
escapeCsvField(rev.dialect ?? ""),
|
|
763
|
-
escapeCsvField(rev.sport ?? ""),
|
|
764
|
-
"",
|
|
765
|
-
"",
|
|
766
|
-
"",
|
|
767
|
-
"",
|
|
768
|
-
""
|
|
769
|
-
];
|
|
770
|
-
lines.push(["revision", ...sessionCols, ...eventCols, ...extraCols].join(","));
|
|
771
|
-
}
|
|
772
|
-
for (const p of bundle.parses ?? []) {
|
|
773
|
-
const sessionCols = new Array(SESSION_HEADER.length).fill("");
|
|
774
|
-
sessionCols[1] = escapeCsvField(p.noteId);
|
|
775
|
-
sessionCols[2] = escapeCsvField(p.blockId ?? "");
|
|
776
|
-
sessionCols[3] = escapeCsvField(p.blockVersion ?? "");
|
|
777
|
-
const eventCols = new Array(EVENT_HEADER.length).fill("");
|
|
778
|
-
eventCols[3] = escapeCsvField(p.timestamp);
|
|
779
|
-
const extraCols = [
|
|
780
|
-
"",
|
|
781
|
-
"",
|
|
782
|
-
"",
|
|
783
|
-
"",
|
|
784
|
-
"",
|
|
785
|
-
escapeCsvField(p.id),
|
|
786
|
-
escapeCsvField(p.stage),
|
|
787
|
-
escapeCsvField(p.status),
|
|
788
|
-
escapeCsvField(p.diagnostics ? JSON.stringify(p.diagnostics) : ""),
|
|
789
|
-
escapeCsvField(p.metrics ? JSON.stringify(p.metrics) : "")
|
|
790
|
-
];
|
|
791
|
-
lines.push(["parse", ...sessionCols, ...eventCols, ...extraCols].join(","));
|
|
792
|
-
}
|
|
793
|
-
const eventsBySession = /* @__PURE__ */ new Map();
|
|
794
|
-
for (const ev of bundle.events) {
|
|
795
|
-
const arr = eventsBySession.get(ev.resultId);
|
|
796
|
-
if (arr) arr.push(ev);
|
|
797
|
-
else eventsBySession.set(ev.resultId, [ev]);
|
|
798
|
-
}
|
|
799
|
-
for (const session of bundle.sessions) {
|
|
800
|
-
const sCells = sessionCells(session);
|
|
801
|
-
const trailingEmpty = new Array(TELEMETRY_EXTRA_COLS.length).fill("");
|
|
802
|
-
lines.push(["session", ...sCells, ...new Array(EVENT_HEADER.length).fill(""), ...trailingEmpty].join(","));
|
|
803
|
-
const ordered = [...eventsBySession.get(session.id) ?? []].sort(
|
|
804
|
-
(a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0
|
|
805
|
-
);
|
|
806
|
-
for (const ev of ordered) {
|
|
807
|
-
const metrics = ev.metrics ?? [];
|
|
808
|
-
if (metrics.length === 0) {
|
|
809
|
-
const emptyMetric = { type: "" };
|
|
810
|
-
lines.push(["event", ...sCells, ...metricCells(ev, emptyMetric, -1), ...trailingEmpty].join(","));
|
|
811
|
-
} else {
|
|
812
|
-
metrics.forEach((m, i) => {
|
|
813
|
-
lines.push(["event", ...sCells, ...metricCells(ev, m, i), ...trailingEmpty].join(","));
|
|
814
|
-
});
|
|
815
|
-
}
|
|
816
|
-
}
|
|
817
|
-
}
|
|
818
|
-
return lines.join("\n") + "\n";
|
|
819
|
-
}
|
|
820
|
-
function csvToTelemetryBundle(csv) {
|
|
821
|
-
const records = splitCsvRecords(csv);
|
|
822
|
-
if (records.length < 2) return { bundles: [], errors: [] };
|
|
823
|
-
const header = parseCsvLine(records[0]);
|
|
824
|
-
if (header[0] !== "recordKind") {
|
|
825
|
-
try {
|
|
826
|
-
const single = csvToSessionRows(csv);
|
|
827
|
-
return {
|
|
828
|
-
bundles: [{ sessions: [single.session], events: single.events }],
|
|
829
|
-
errors: []
|
|
830
|
-
};
|
|
831
|
-
} catch (err) {
|
|
832
|
-
return { bundles: [], errors: [err instanceof Error ? err.message : String(err)] };
|
|
833
|
-
}
|
|
834
|
-
}
|
|
835
|
-
const col = /* @__PURE__ */ new Map();
|
|
836
|
-
header.forEach((name, idx) => col.set(name, idx));
|
|
837
|
-
const at = (cells, name) => {
|
|
838
|
-
const idx = col.get(name);
|
|
839
|
-
return idx === void 0 ? "" : cells[idx] ?? "";
|
|
840
|
-
};
|
|
841
|
-
const revisionsByNote = /* @__PURE__ */ new Map();
|
|
842
|
-
const parsesByNote = /* @__PURE__ */ new Map();
|
|
843
|
-
const sessionCsvLinesBySession = /* @__PURE__ */ new Map();
|
|
844
|
-
const errors = [];
|
|
845
|
-
for (const [idx, line] of records.slice(1).entries()) {
|
|
846
|
-
const cells = parseCsvLine(line);
|
|
847
|
-
if (cells.length === 1 && cells[0] === "") continue;
|
|
848
|
-
const kind = at(cells, "recordKind");
|
|
849
|
-
const noteId = nonempty(at(cells, "noteId"));
|
|
850
|
-
if (!noteId) {
|
|
851
|
-
errors.push(`Row ${idx + 2}: missing noteId`);
|
|
852
|
-
continue;
|
|
853
|
-
}
|
|
854
|
-
if (kind === "revision") {
|
|
855
|
-
const revKind = nonempty(at(cells, "revisionKind"));
|
|
856
|
-
const blockId = nonempty(at(cells, "blockId"));
|
|
857
|
-
const version = num(at(cells, "blockVersion"));
|
|
858
|
-
const savedAt = num(at(cells, "revisionSavedAt"));
|
|
859
|
-
if (!revKind || !blockId || !version || savedAt === void 0) {
|
|
860
|
-
errors.push(`Row ${idx + 2}: invalid revision columns`);
|
|
861
|
-
continue;
|
|
862
|
-
}
|
|
863
|
-
const rev = {
|
|
864
|
-
noteId,
|
|
865
|
-
blockId,
|
|
866
|
-
version,
|
|
867
|
-
kind: revKind,
|
|
868
|
-
rawContent: at(cells, "revisionRawContent"),
|
|
869
|
-
savedAt,
|
|
870
|
-
...nonempty(at(cells, "revisionDialect")) ? { dialect: nonempty(at(cells, "revisionDialect")) } : {},
|
|
871
|
-
...nonempty(at(cells, "revisionSport")) ? { sport: nonempty(at(cells, "revisionSport")) } : {}
|
|
872
|
-
};
|
|
873
|
-
const list = revisionsByNote.get(noteId) ?? [];
|
|
874
|
-
list.push(rev);
|
|
875
|
-
revisionsByNote.set(noteId, list);
|
|
876
|
-
} else if (kind === "parse") {
|
|
877
|
-
const id = nonempty(at(cells, "parseId"));
|
|
878
|
-
const stage = nonempty(at(cells, "parseStage"));
|
|
879
|
-
const status = nonempty(at(cells, "parseStatus"));
|
|
880
|
-
const timestamp = num(at(cells, "timestamp"));
|
|
881
|
-
if (!id || !stage || !status || timestamp === void 0) {
|
|
882
|
-
errors.push(`Row ${idx + 2}: invalid parse columns`);
|
|
883
|
-
continue;
|
|
884
|
-
}
|
|
885
|
-
const parseRec = {
|
|
886
|
-
id,
|
|
887
|
-
noteId,
|
|
888
|
-
...nonempty(at(cells, "blockId")) ? { blockId: nonempty(at(cells, "blockId")) } : {},
|
|
889
|
-
...num(at(cells, "blockVersion")) !== void 0 ? { blockVersion: num(at(cells, "blockVersion")) } : {},
|
|
890
|
-
stage,
|
|
891
|
-
status,
|
|
892
|
-
timestamp,
|
|
893
|
-
...nonempty(at(cells, "parseDiagnosticsJson")) ? { diagnostics: jsonCell(at(cells, "parseDiagnosticsJson")) } : {},
|
|
894
|
-
...nonempty(at(cells, "parseMetricsJson")) ? { metrics: jsonCell(at(cells, "parseMetricsJson")) } : {}
|
|
895
|
-
};
|
|
896
|
-
const list = parsesByNote.get(noteId) ?? [];
|
|
897
|
-
list.push(parseRec);
|
|
898
|
-
parsesByNote.set(noteId, list);
|
|
899
|
-
} else if (kind === "session" || kind === "event") {
|
|
900
|
-
const sessionId = nonempty(at(cells, "sessionId"));
|
|
901
|
-
if (!sessionId) {
|
|
902
|
-
errors.push(`Row ${idx + 2}: missing sessionId`);
|
|
903
|
-
continue;
|
|
904
|
-
}
|
|
905
|
-
const subCells = SESSION_CSV_HEADER.map((h) => escapeCsvField(at(cells, h)));
|
|
906
|
-
const bucket = sessionCsvLinesBySession.get(sessionId) ?? {
|
|
907
|
-
noteId,
|
|
908
|
-
lines: [SESSION_CSV_HEADER.join(",")]
|
|
909
|
-
};
|
|
910
|
-
bucket.lines.push(subCells.join(","));
|
|
911
|
-
sessionCsvLinesBySession.set(sessionId, bucket);
|
|
912
|
-
} else {
|
|
913
|
-
errors.push(`Row ${idx + 2}: unknown recordKind '${kind}'`);
|
|
914
|
-
}
|
|
915
|
-
}
|
|
916
|
-
const bundlesByNote = /* @__PURE__ */ new Map();
|
|
917
|
-
const ensureBundle = (noteId) => {
|
|
918
|
-
const existing = bundlesByNote.get(noteId);
|
|
919
|
-
if (existing) return existing;
|
|
920
|
-
const created = { sessions: [], events: [] };
|
|
921
|
-
bundlesByNote.set(noteId, created);
|
|
922
|
-
return created;
|
|
923
|
-
};
|
|
924
|
-
for (const [noteId, revs] of revisionsByNote) {
|
|
925
|
-
ensureBundle(noteId).revisions = revs;
|
|
926
|
-
}
|
|
927
|
-
for (const [noteId, parses] of parsesByNote) {
|
|
928
|
-
ensureBundle(noteId).parses = parses;
|
|
929
|
-
}
|
|
930
|
-
for (const [, { noteId, lines }] of sessionCsvLinesBySession) {
|
|
931
|
-
try {
|
|
932
|
-
const parsed = csvToSessionRows(lines.join("\n") + "\n");
|
|
933
|
-
const bundle = ensureBundle(noteId);
|
|
934
|
-
bundle.sessions.push(parsed.session);
|
|
935
|
-
bundle.events.push(...parsed.events);
|
|
936
|
-
} catch (err) {
|
|
937
|
-
errors.push(err instanceof Error ? err.message : String(err));
|
|
938
|
-
}
|
|
939
|
-
}
|
|
940
|
-
return { bundles: [...bundlesByNote.values()], errors };
|
|
941
|
-
}
|
|
942
|
-
|
|
943
|
-
// src/version.ts
|
|
944
|
-
var VERSION = "0.53.2204";
|
|
945
|
-
var GIT_SHA = "5497f33";
|
|
946
|
-
var BUILD_TIME = "2026-11-11T22:37:09.862Z";
|
|
947
|
-
var SEMVER = {
|
|
948
|
-
version: "0.53.2204",
|
|
949
|
-
gitSha: "5497f33",
|
|
950
|
-
buildTime: "2026-11-11T22:37:09.862Z"
|
|
951
|
-
};
|
|
952
|
-
var SEED_SCHEMA = 9;
|
|
953
|
-
var SEED_REGISTERED_WIDGETS = KNOWN_SECTION_WIDGETS;
|
|
954
|
-
var SEED_NAMESPACE = "1b671a64-40d5-491e-99b0-da01ff1f3341";
|
|
955
|
-
var SEED_PRECEDENCE_RANK = {
|
|
956
|
-
core: 0,
|
|
957
|
-
community: 1,
|
|
958
|
-
imported: 2,
|
|
959
|
-
user: 3
|
|
960
|
-
};
|
|
961
|
-
function seedSourceTier(sourceIdOrMetaKey, explicitTier) {
|
|
962
|
-
if (explicitTier) return explicitTier;
|
|
963
|
-
if (!sourceIdOrMetaKey) return "core";
|
|
964
|
-
if (sourceIdOrMetaKey === "user") return "user";
|
|
965
|
-
const id = sourceIdOrMetaKey.startsWith("seed:") ? sourceIdOrMetaKey.slice(5) : sourceIdOrMetaKey;
|
|
966
|
-
if (id === "core" || id === "efforts" || id === "equipment") return "core";
|
|
967
|
-
if (id === "community" || id.startsWith("community-") || id === "common") return "community";
|
|
968
|
-
return "imported";
|
|
969
|
-
}
|
|
970
|
-
function seedPrecedenceRank(sourceIdOrMetaKey, explicitTier) {
|
|
971
|
-
return SEED_PRECEDENCE_RANK[seedSourceTier(sourceIdOrMetaKey, explicitTier)];
|
|
972
|
-
}
|
|
973
|
-
var SEED_BROADCAST_CHANNEL = "wodwiki.seed";
|
|
974
|
-
var EFFORTS_CHUNK_ID = "efforts";
|
|
975
|
-
var EQUIPMENT_CHUNK_ID = "equipment";
|
|
976
|
-
var CANVAS_CHUNK_ID = "canvas";
|
|
977
|
-
var DASHBOARDS_CHUNK_ID = "dashboards";
|
|
978
|
-
function seedMetaKey(sourceId) {
|
|
979
|
-
return `seed:${sourceId}`;
|
|
980
|
-
}
|
|
981
|
-
function feedIdOfMetaKey(metaKey) {
|
|
982
|
-
return metaKey.startsWith("seed:") ? metaKey.slice(5) : metaKey;
|
|
983
|
-
}
|
|
984
|
-
function emptySeedMeta(key) {
|
|
985
|
-
return { key, schema: SEED_SCHEMA, seedVersion: 0, builtAt: "", importedAt: 0, chunks: {}, claim: null };
|
|
986
|
-
}
|
|
987
|
-
function notebookSlugForChunkId(chunkId) {
|
|
988
|
-
const value = /^notebook\.(.+)$/.exec(chunkId)?.[1];
|
|
989
|
-
return value && value !== "_root" ? value : void 0;
|
|
990
|
-
}
|
|
991
|
-
function canvasRouteSlug(content) {
|
|
992
|
-
const fm = /^---\r?\n([\s\S]*?)\r?\n---/.exec(content);
|
|
993
|
-
if (fm?.[1] && !/^template:\s*canvas\s*$/m.test(fm[1])) return null;
|
|
994
|
-
return fm?.[1]?.match(/^route:\s*(\S+)\s*$/m)?.[1]?.replace(/^\//, "") || null;
|
|
995
|
-
}
|
|
996
|
-
function seedNoteSourceId(path, content, chunkId) {
|
|
997
|
-
const parts = path.split("/");
|
|
998
|
-
const stem = (parts.at(-1) ?? "").replace(/\.md$/i, "");
|
|
999
|
-
const under = parts.slice(2).map((p) => p.replace(/\.md$/i, "")).join("/");
|
|
1000
|
-
if (chunkId === CANVAS_CHUNK_ID) return `guides:${canvasRouteSlug(content) ?? under}`;
|
|
1001
|
-
if (chunkId === DASHBOARDS_CHUNK_ID) return "dashboards";
|
|
1002
|
-
if (chunkId === EFFORTS_CHUNK_ID) return "efforts";
|
|
1003
|
-
if (chunkId === EQUIPMENT_CHUNK_ID) return "equipment";
|
|
1004
|
-
if (chunkId.startsWith("notebook.")) {
|
|
1005
|
-
const slug = notebookSlugForChunkId(chunkId);
|
|
1006
|
-
return !slug ? "notebook:_root" : stem.toLowerCase() === "readme" ? `notebook:${slug}` : `notebook:${under}`;
|
|
1007
|
-
}
|
|
1008
|
-
return void 0;
|
|
1009
|
-
}
|
|
1010
|
-
function object(value) {
|
|
1011
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1012
|
-
}
|
|
1013
|
-
function positive(value) {
|
|
1014
|
-
return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
|
|
1015
|
-
}
|
|
1016
|
-
function nonnegative(value) {
|
|
1017
|
-
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
|
|
1018
|
-
}
|
|
1019
|
-
function finite(value) {
|
|
1020
|
-
return typeof value === "number" && Number.isFinite(value);
|
|
1021
|
-
}
|
|
1022
|
-
function assertSeedManifest(value) {
|
|
1023
|
-
if (!object(value) || value.schema !== SEED_SCHEMA) throw new Error("Incompatible seed schema; rebuild seed artifacts");
|
|
1024
|
-
if (!nonnegative(value.version) || typeof value.builtAt !== "string" || !Number.isFinite(Date.parse(value.builtAt)) || !Array.isArray(value.chunks)) throw new Error("seed manifest failed shape validation");
|
|
1025
|
-
for (const key of ["versionLabel", "commit", "name", "description"]) if (value[key] !== void 0 && typeof value[key] !== "string") throw new Error("invalid seed manifest metadata");
|
|
1026
|
-
if (value.repositoryUrl !== void 0 && (typeof value.repositoryUrl !== "string" || !/^https:\/\//.test(value.repositoryUrl) || new URL(value.repositoryUrl).username || new URL(value.repositoryUrl).password)) throw new Error("invalid seed repository URL");
|
|
1027
|
-
if (value.dirty !== void 0 && typeof value.dirty !== "boolean") throw new Error("invalid seed manifest metadata");
|
|
1028
|
-
const ids = /* @__PURE__ */ new Set(), paths = /* @__PURE__ */ new Set();
|
|
1029
|
-
for (const chunk of value.chunks) {
|
|
1030
|
-
if (!object(chunk) || typeof chunk.id !== "string" || !chunk.id || typeof chunk.path !== "string" || !/^chunks\/[a-zA-Z0-9._-]+\.json$/.test(chunk.path) || typeof chunk.sha256 !== "string" || !/^[0-9a-f]{64}$/.test(chunk.sha256) || !nonnegative(chunk.bytes) || !nonnegative(chunk.count) || chunk.kind !== void 0 && chunk.kind !== "notes" || ids.has(chunk.id) || paths.has(chunk.path)) throw new Error("seed manifest failed shape validation");
|
|
1031
|
-
ids.add(chunk.id);
|
|
1032
|
-
paths.add(chunk.path);
|
|
1033
|
-
}
|
|
1034
|
-
if (value.notebooks !== void 0) {
|
|
1035
|
-
if (!Array.isArray(value.notebooks)) throw new Error("seed manifest failed shape validation");
|
|
1036
|
-
for (const nb of value.notebooks) {
|
|
1037
|
-
if (!object(nb) || typeof nb.notebookId !== "string" || !nb.notebookId || typeof nb.label !== "string" || !nonnegative(nb.count) || typeof nb.indexPath !== "string" || !nb.indexPath || !nonnegative(nb.version) || typeof nb.commit !== "string" || typeof nb.builtAt !== "string" || typeof nb.sha256 !== "string" || !nonnegative(nb.bytes)) {
|
|
1038
|
-
throw new Error("seed manifest failed shape validation");
|
|
1039
|
-
}
|
|
1040
|
-
if ("records" in nb && Array.isArray(nb.records)) {
|
|
1041
|
-
throw new Error("seed manifest failed shape validation: manifest.notebooks must not contain inline records");
|
|
1042
|
-
}
|
|
1043
|
-
}
|
|
1044
|
-
}
|
|
1045
|
-
return value;
|
|
1046
|
-
}
|
|
1047
|
-
function assertNotebookIndex(value) {
|
|
1048
|
-
if (!object(value)) throw new Error("notebook index failed shape validation");
|
|
1049
|
-
if (typeof value.notebookId !== "string" || !value.notebookId || typeof value.label !== "string" || !value.label || typeof value.indexPath !== "string" || !value.indexPath || !nonnegative(value.version) || typeof value.commit !== "string" || typeof value.builtAt !== "string" || typeof value.sha256 !== "string" || !nonnegative(value.bytes) || !nonnegative(value.count) || !Array.isArray(value.records)) {
|
|
1050
|
-
throw new Error("notebook index failed shape validation: missing required index summary or records");
|
|
1051
|
-
}
|
|
1052
|
-
for (const r of value.records) {
|
|
1053
|
-
if (!object(r) || typeof r.uuid !== "string" || typeof r.path !== "string" || typeof r.recordPath !== "string" || typeof r.commit !== "string" || !nonnegative(r.version) || typeof r.sha256 !== "string") {
|
|
1054
|
-
throw new Error("notebook index failed shape validation: invalid record ref");
|
|
1055
|
-
}
|
|
1056
|
-
}
|
|
1057
|
-
return value;
|
|
1058
|
-
}
|
|
1059
|
-
function assertTelemetry(row, blockIndex) {
|
|
1060
|
-
if (row.telemetry === void 0) return;
|
|
1061
|
-
if (!object(row.telemetry) || !Array.isArray(row.telemetry.sessions) || !Array.isArray(row.telemetry.events)) throw new Error("invalid seed telemetry");
|
|
1062
|
-
const sessions = /* @__PURE__ */ new Map();
|
|
1063
|
-
for (const session of row.telemetry.sessions) {
|
|
1064
|
-
if (!object(session) || typeof session.id !== "string" || !session.id || sessions.has(session.id) || typeof session.noteId !== "string" || !session.noteId || typeof row.uuid === "string" && session.noteId !== row.uuid || typeof session.blockId !== "string" || !positive(session.blockVersion) || typeof session.blockContentId !== "string" || !finite(session.startTime) || !finite(session.endTime) || !finite(session.duration) || typeof session.completed !== "boolean" || !finite(session.createdAt)) throw new Error("invalid seed session");
|
|
1065
|
-
const projection = blockIndex.find((candidate) => object(candidate) && candidate.blockId === session.blockId);
|
|
1066
|
-
if (!object(projection) || projection.dataType !== "wod" || projection.blockVersion !== session.blockVersion || projection.blockContentId !== session.blockContentId) throw new Error("orphan or incompatible seed session pin");
|
|
1067
|
-
sessions.set(session.id, session);
|
|
1068
|
-
}
|
|
1069
|
-
const eventIds = /* @__PURE__ */ new Set();
|
|
1070
|
-
for (const event of row.telemetry.events) {
|
|
1071
|
-
if (!object(event) || typeof event.id !== "string" || !event.id || eventIds.has(event.id) || typeof event.resultId !== "string" || typeof event.noteId !== "string" || !finite(event.timestamp) || event.grain !== "event" && event.grain !== "summary" || typeof event.outputType !== "string" || !Array.isArray(event.metrics) || !event.metrics.every((metric) => object(metric) && typeof metric.type === "string") || event.grain === "summary" && event.metrics.length !== 1) throw new Error("invalid seed event");
|
|
1072
|
-
const session = sessions.get(event.resultId);
|
|
1073
|
-
if (!session || event.noteId !== session.noteId || event.blockId !== session.blockId || event.blockVersion !== session.blockVersion || event.blockContentId !== session.blockContentId) {
|
|
1074
|
-
throw new Error("orphan or incompatible seed event identity");
|
|
1075
|
-
}
|
|
1076
|
-
eventIds.add(event.id);
|
|
1077
|
-
}
|
|
1078
|
-
}
|
|
1079
|
-
function assertSeedRows(value) {
|
|
1080
|
-
if (!Array.isArray(value)) throw new Error("seed chunk is not an array");
|
|
1081
|
-
const paths = /* @__PURE__ */ new Set();
|
|
1082
|
-
for (const row of value) {
|
|
1083
|
-
if (!object(row) || typeof row.path !== "string" || !row.path || row.path.startsWith("/") || row.path.split("/").includes("..") || paths.has(row.path) || typeof row.content !== "string" || !object(row.blocks) || !Array.isArray(row.blockIndex) || !Array.isArray(row.blockEfforts) || !Array.isArray(row.blockEquipment)) throw new Error("seed chunk row failed shape validation");
|
|
1084
|
-
paths.add(row.path);
|
|
1085
|
-
for (const [id, block] of Object.entries(row.blocks)) {
|
|
1086
|
-
if (!object(block) || block.id !== id || !id || block.version !== 1 || block.sourceRevision !== 1 || !nonnegative(block.from) || !positive(block.to) || block.from >= block.to || block.to > row.content.length || !["wod", "query", "widget", "embed"].includes(String(block.kind)) || (block.kind === "wod" ? !["time", "log"].includes(String(block.dialect)) : block.dialect !== void 0) || block.sport !== void 0 && typeof block.sport !== "string") throw new Error("invalid seed block range or revision");
|
|
1087
|
-
}
|
|
1088
|
-
validateNoteBlocks(row.content, row.blocks, 1, { registeredWidgets: SEED_REGISTERED_WIDGETS });
|
|
1089
|
-
const indexed = /* @__PURE__ */ new Set();
|
|
1090
|
-
const sections = parseDocumentSections(row.content, { registeredWidgets: SEED_REGISTERED_WIDGETS });
|
|
1091
|
-
for (const projection of row.blockIndex) {
|
|
1092
|
-
if (!object(projection) || typeof projection.blockId !== "string") throw new Error("invalid seed projection");
|
|
1093
|
-
const block = row.blocks[projection.blockId];
|
|
1094
|
-
if (!object(block) || indexed.has(projection.blockId) || typeof projection.id !== "string" || typeof projection.noteId !== "string" || projection.id !== `${projection.noteId}:${projection.blockId}` || projection.blockVersion !== 1 || projection.sourceRevision !== 1 || projection.from !== block.from || projection.to !== block.to || projection.dataType !== block.kind || projection.rawContent !== row.content.slice(Number(block.from), Number(block.to)) || typeof projection.noteTitle !== "string" || typeof projection.createdAt !== "number" || !Number.isFinite(projection.createdAt) || projection.sourcePath !== row.path || projection.isStatic !== true) throw new Error("orphan or incompatible seed projection");
|
|
1095
|
-
if ("segmentId" in projection || "segmentVersion" in projection) throw new Error("incompatible seed projection");
|
|
1096
|
-
for (const key of ["sourceId", "routeId", "blockContentId"]) if (projection[key] !== void 0 && typeof projection[key] !== "string") throw new Error("invalid seed projection metadata");
|
|
1097
|
-
if (projection.position !== void 0 && !nonnegative(projection.position)) throw new Error("invalid seed projection position");
|
|
1098
|
-
if (block.kind === "wod") {
|
|
1099
|
-
const section = sections.find((s) => s.from === block.from && s.to === block.to);
|
|
1100
|
-
if (projection.blockContentId !== blockContentId(section?.scriptBlock?.content ?? row.content.slice(Number(block.from), Number(block.to)))) throw new Error("invalid seed workout fingerprint");
|
|
1101
|
-
} else if (projection.blockContentId !== void 0) throw new Error("non-workout seed fingerprint");
|
|
1102
|
-
indexed.add(projection.blockId);
|
|
1103
|
-
}
|
|
1104
|
-
if (indexed.size !== Object.keys(row.blocks).length) throw new Error("missing actionable seed projection");
|
|
1105
|
-
const links = /* @__PURE__ */ new Set();
|
|
1106
|
-
for (const link of row.blockEfforts) {
|
|
1107
|
-
if (!object(link) || typeof link.blockId !== "string" || typeof link.noteId !== "string" || typeof link.effortSlug !== "string" || !link.effortSlug) throw new Error("invalid seed effort identity");
|
|
1108
|
-
const block = row.blocks[link.blockId];
|
|
1109
|
-
if (link.id !== `${link.noteId}:${link.blockId}:${link.effortSlug}` || links.has(String(link.id)) || !object(block) || block.kind !== "wod" || !indexed.has(link.blockId) || link.sourcePath !== row.path || link.isStatic !== true || typeof link.createdAt !== "number") throw new Error("orphan or incompatible seed effort link");
|
|
1110
|
-
const projection = row.blockIndex.find((p) => object(p) && p.blockId === link.blockId);
|
|
1111
|
-
if (!object(projection) || link.noteId !== projection.noteId || link.blockContentId !== projection.blockContentId || !Number.isFinite(link.createdAt)) throw new Error("invalid seed effort metadata");
|
|
1112
|
-
links.add(String(link.id));
|
|
1113
|
-
}
|
|
1114
|
-
const equipmentLinks = /* @__PURE__ */ new Set();
|
|
1115
|
-
for (const link of row.blockEquipment) {
|
|
1116
|
-
if (!object(link) || typeof link.blockId !== "string" || typeof link.noteId !== "string" || typeof link.equipmentSlug !== "string" || !link.equipmentSlug) throw new Error("invalid seed equipment identity");
|
|
1117
|
-
const block = row.blocks[link.blockId];
|
|
1118
|
-
if (link.id !== `${link.noteId}:${link.blockId}:${link.equipmentSlug}` || equipmentLinks.has(String(link.id)) || !object(block) || block.kind !== "wod" || !indexed.has(link.blockId) || link.sourcePath !== row.path || link.isStatic !== true || typeof link.createdAt !== "number") throw new Error("orphan or incompatible seed equipment link");
|
|
1119
|
-
const projection = row.blockIndex.find((p) => object(p) && p.blockId === link.blockId);
|
|
1120
|
-
if (!object(projection) || link.noteId !== projection.noteId || link.blockContentId !== projection.blockContentId || !Number.isFinite(link.createdAt)) throw new Error("invalid seed equipment metadata");
|
|
1121
|
-
equipmentLinks.add(String(link.id));
|
|
1122
|
-
}
|
|
1123
|
-
assertTelemetry(row, row.blockIndex);
|
|
1124
|
-
}
|
|
1125
|
-
return value;
|
|
1126
|
-
}
|
|
1127
|
-
function assertSeedRow(value) {
|
|
1128
|
-
return assertSeedRows([value])[0];
|
|
1129
|
-
}
|
|
1130
|
-
function makeScopedOverrideId(notebookId, kind, slug) {
|
|
1131
|
-
return `${notebookId}:${kind}:${slug}`;
|
|
1132
|
-
}
|
|
1133
|
-
function contributionsFromParsedTag(parsed) {
|
|
1134
|
-
const contributions = [];
|
|
1135
|
-
for (const [mKey, mVal] of Object.entries(parsed.metrics)) {
|
|
1136
|
-
if (typeof mVal !== "string" && typeof mVal !== "number") continue;
|
|
1137
|
-
const strVal = String(mVal).trim();
|
|
1138
|
-
const qtyMatch = strVal.match(/^([+-]?\d+(?:\.\d+)?)\s*([A-Za-z%/][\w%/.-]*)$/);
|
|
1139
|
-
if (qtyMatch) {
|
|
1140
|
-
contributions.push({ kind: "metric", type: mKey, value: Number(qtyMatch[1]), unit: qtyMatch[2] });
|
|
1141
|
-
} else {
|
|
1142
|
-
contributions.push({ kind: "metric", type: mKey, value: mVal });
|
|
1143
|
-
}
|
|
1144
|
-
}
|
|
1145
|
-
for (const [sKey, sExpr] of Object.entries(parsed.summaries)) {
|
|
1146
|
-
contributions.push({ kind: "metric", type: `summaries.${sKey}`, value: sExpr });
|
|
1147
|
-
}
|
|
1148
|
-
for (const [wKey, wSpec] of Object.entries(parsed.widgets ?? {})) {
|
|
1149
|
-
contributions.push({ kind: "metric", type: `widgets.${wKey}`, value: wSpec });
|
|
1150
|
-
}
|
|
1151
|
-
for (const tSlug of parsed.tags) {
|
|
1152
|
-
contributions.push({ kind: "tag", slug: tSlug });
|
|
1153
|
-
}
|
|
1154
|
-
for (const fnName of parsed.functions) {
|
|
1155
|
-
contributions.push({ kind: "function", name: fnName });
|
|
1156
|
-
}
|
|
1157
|
-
return contributions;
|
|
1158
|
-
}
|
|
1159
|
-
async function saveScopedPropertyOverride(storage, input) {
|
|
1160
|
-
const targetNotebookId = toNotebookId$1(input.targetNotebookId);
|
|
1161
|
-
if (isSystemReadOnlyNotebook(targetNotebookId)) {
|
|
1162
|
-
throw new Error(`Notebook '${targetNotebookId}' is read-only and cannot store overrides.`);
|
|
1163
|
-
}
|
|
1164
|
-
if (targetNotebookId === "notebook/journal" || targetNotebookId === "notebook/playground") {
|
|
1165
|
-
throw new Error(
|
|
1166
|
-
`Property overrides belong in 'notebook/custom' or a shared user Notebook, not '${targetNotebookId}'.`
|
|
1167
|
-
);
|
|
1168
|
-
}
|
|
1169
|
-
const cleanSlug = input.slug.trim().toLowerCase();
|
|
1170
|
-
if (!cleanSlug) {
|
|
1171
|
-
throw new Error("Property override requires a non-empty canonical slug.");
|
|
1172
|
-
}
|
|
1173
|
-
const nbSlug = notebookSlugFromId$1(targetNotebookId);
|
|
1174
|
-
const ownerNoteId = `override/${nbSlug}/${input.kind}/${cleanSlug}`;
|
|
1175
|
-
const deterministicEntityId = `${input.kind}-override-${nbSlug}-${cleanSlug}`;
|
|
1176
|
-
const now = Date.now();
|
|
1177
|
-
let rawContent = input.rawContent;
|
|
1178
|
-
const fm = readFrontmatterMeta(rawContent);
|
|
1179
|
-
if (typeof fm["id"] !== "string" || !fm["id"].trim()) {
|
|
1180
|
-
rawContent = patchFrontmatterProperty(rawContent, ["id"], deterministicEntityId);
|
|
1181
|
-
}
|
|
1182
|
-
if (typeof fm["slug"] !== "string" || fm["slug"].trim() !== cleanSlug) {
|
|
1183
|
-
rawContent = patchFrontmatterProperty(rawContent, ["slug"], cleanSlug);
|
|
1184
|
-
}
|
|
1185
|
-
let label = input.title?.trim() || cleanSlug;
|
|
1186
|
-
let payload;
|
|
1187
|
-
if (input.kind === "effort") {
|
|
1188
|
-
const parsed = documentToEffort(rawContent);
|
|
1189
|
-
if (parsed.errors.length > 0) {
|
|
1190
|
-
throw new Error(parsed.errors.join("\n"));
|
|
1191
|
-
}
|
|
1192
|
-
label = parsed.effort.label || label;
|
|
1193
|
-
const effort = {
|
|
1194
|
-
...parsed.effort,
|
|
1195
|
-
id: typeof fm["id"] === "string" && fm["id"].trim() ? fm["id"].trim() : deterministicEntityId,
|
|
1196
|
-
slug: cleanSlug,
|
|
1197
|
-
label,
|
|
1198
|
-
registrySource: "user",
|
|
1199
|
-
ownerNoteId,
|
|
1200
|
-
sourceId: targetNotebookId,
|
|
1201
|
-
updatedAt: new Date(now).toISOString()
|
|
1202
|
-
};
|
|
1203
|
-
payload = effort;
|
|
1204
|
-
} else if (input.kind === "equipment") {
|
|
1205
|
-
const parsed = documentToEquipment(rawContent);
|
|
1206
|
-
if (parsed.errors.length > 0) {
|
|
1207
|
-
throw new Error(parsed.errors.join("\n"));
|
|
1208
|
-
}
|
|
1209
|
-
label = parsed.equipment.label || label;
|
|
1210
|
-
const equipment = {
|
|
1211
|
-
...parsed.equipment,
|
|
1212
|
-
id: typeof fm["id"] === "string" && fm["id"].trim() ? fm["id"].trim() : deterministicEntityId,
|
|
1213
|
-
slug: cleanSlug,
|
|
1214
|
-
label,
|
|
1215
|
-
registrySource: "user",
|
|
1216
|
-
ownerNoteId,
|
|
1217
|
-
sourceId: targetNotebookId,
|
|
1218
|
-
updatedAt: new Date(now).toISOString()
|
|
1219
|
-
};
|
|
1220
|
-
payload = equipment;
|
|
1221
|
-
} else if (input.kind === "tag") {
|
|
1222
|
-
const category = input.category ?? "tag";
|
|
1223
|
-
const parsed = documentToTag(rawContent, category);
|
|
1224
|
-
if (parsed.errors.length > 0) {
|
|
1225
|
-
throw new Error(parsed.errors.join("\n"));
|
|
1226
|
-
}
|
|
1227
|
-
const resolvedCat = parsed.tag.category || category;
|
|
1228
|
-
label = parsed.tag.label || label;
|
|
1229
|
-
const tagRow = {
|
|
1230
|
-
id: parsed.tag.id || deterministicEntityId,
|
|
1231
|
-
label: cleanSlug,
|
|
1232
|
-
...resolvedCat !== "tag" ? { type: resolvedCat } : {},
|
|
1233
|
-
contributions: contributionsFromParsedTag(parsed.tag),
|
|
1234
|
-
createdAt: now
|
|
1235
|
-
};
|
|
1236
|
-
payload = tagRow;
|
|
1237
|
-
} else {
|
|
1238
|
-
const parsed = documentToTag(rawContent, "tag");
|
|
1239
|
-
const contributions = contributionsFromParsedTag(parsed.tag);
|
|
1240
|
-
label = typeof fm["label"] === "string" && fm["label"].trim() || label;
|
|
1241
|
-
const tagTypeRow = {
|
|
1242
|
-
id: deterministicEntityId,
|
|
1243
|
-
name: cleanSlug,
|
|
1244
|
-
label,
|
|
1245
|
-
...typeof fm["color"] === "string" && fm["color"].trim() ? { color: fm["color"].trim() } : {},
|
|
1246
|
-
...contributions.length > 0 ? { contributions } : {},
|
|
1247
|
-
createdAt: now
|
|
1248
|
-
};
|
|
1249
|
-
payload = tagTypeRow;
|
|
1250
|
-
}
|
|
1251
|
-
const overrideRecord = {
|
|
1252
|
-
id: makeScopedOverrideId(targetNotebookId, input.kind, cleanSlug),
|
|
1253
|
-
notebookId: targetNotebookId,
|
|
1254
|
-
kind: input.kind,
|
|
1255
|
-
slug: cleanSlug,
|
|
1256
|
-
label,
|
|
1257
|
-
ownerNoteId,
|
|
1258
|
-
rawContent,
|
|
1259
|
-
payload,
|
|
1260
|
-
seedOrigin: "user",
|
|
1261
|
-
updatedAt: now
|
|
1262
|
-
};
|
|
1263
|
-
await storage.transaction(
|
|
1264
|
-
["notes", "block_revisions", "property_overrides", "tags", "tag_types"],
|
|
1265
|
-
"readwrite",
|
|
1266
|
-
async (tx) => {
|
|
1267
|
-
const landing = await tx.readonly("notes").get(targetNotebookId);
|
|
1268
|
-
if (landing && (landing.feedOrigin === "feed" || landing.seedOrigin === "seed")) {
|
|
1269
|
-
throw new Error(`Notebook '${targetNotebookId}' is feed-delivered and read-only.`);
|
|
1270
|
-
}
|
|
1271
|
-
const priorNote = await tx.readonly("notes").get(ownerNoteId);
|
|
1272
|
-
const nextRev = (priorNote?.sourceRevision ?? 0) + 1;
|
|
1273
|
-
const blocks = reconcileNoteBlocks(rawContent, {
|
|
1274
|
-
sourceRevision: nextRev,
|
|
1275
|
-
registeredWidgets: KNOWN_SECTION_WIDGETS
|
|
1276
|
-
});
|
|
1277
|
-
const revisions = Object.values(blocks).map((b) => ({
|
|
1278
|
-
noteId: ownerNoteId,
|
|
1279
|
-
blockId: b.id,
|
|
1280
|
-
version: b.version,
|
|
1281
|
-
kind: b.kind,
|
|
1282
|
-
rawContent: rawContent.slice(b.from, b.to),
|
|
1283
|
-
savedAt: now,
|
|
1284
|
-
...b.dialect ? { dialect: b.dialect } : {},
|
|
1285
|
-
...b.sport ? { sport: b.sport } : {}
|
|
1286
|
-
}));
|
|
1287
|
-
await tx.readwrite("notes").put({
|
|
1288
|
-
id: ownerNoteId,
|
|
1289
|
-
title: label,
|
|
1290
|
-
rawContent,
|
|
1291
|
-
sourceRevision: nextRev,
|
|
1292
|
-
blocks,
|
|
1293
|
-
createdAt: priorNote?.createdAt ?? now,
|
|
1294
|
-
notebookId: targetNotebookId,
|
|
1295
|
-
notebookIds: [targetNotebookId],
|
|
1296
|
-
seedOrigin: "user"
|
|
1297
|
-
});
|
|
1298
|
-
if (revisions.length > 0) {
|
|
1299
|
-
await tx.readwrite("block_revisions").putMany(revisions);
|
|
1300
|
-
}
|
|
1301
|
-
await tx.readwrite("property_overrides").put(overrideRecord);
|
|
1302
|
-
if (targetNotebookId === "notebook/custom") {
|
|
1303
|
-
if (input.kind === "tag") {
|
|
1304
|
-
await tx.readwrite("tags").put(payload);
|
|
1305
|
-
} else if (input.kind === "tag-type") {
|
|
1306
|
-
await tx.readwrite("tag_types").put(payload);
|
|
1307
|
-
}
|
|
1308
|
-
}
|
|
1309
|
-
}
|
|
1310
|
-
);
|
|
1311
|
-
return overrideRecord;
|
|
1312
|
-
}
|
|
1313
|
-
async function listScopedPropertyOverrides(storage, filter) {
|
|
1314
|
-
let rows;
|
|
1315
|
-
try {
|
|
1316
|
-
if (filter?.notebookId) {
|
|
1317
|
-
rows = await storage.readonly("property_overrides").getAllFromIndex("by-notebook", filter.notebookId);
|
|
1318
|
-
} else if (filter?.kind && filter?.slug) {
|
|
1319
|
-
rows = await storage.readonly("property_overrides").getAllFromIndex("by-kind-slug", [filter.kind, filter.slug]);
|
|
1320
|
-
} else {
|
|
1321
|
-
rows = await storage.readonly("property_overrides").getAll();
|
|
1322
|
-
}
|
|
1323
|
-
} catch {
|
|
1324
|
-
return [];
|
|
1325
|
-
}
|
|
1326
|
-
return rows.filter((r) => {
|
|
1327
|
-
if (filter?.notebookId && r.notebookId !== filter.notebookId) return false;
|
|
1328
|
-
if (filter?.kind && r.kind !== filter.kind) return false;
|
|
1329
|
-
if (filter?.slug && r.slug !== filter.slug) return false;
|
|
1330
|
-
return true;
|
|
1331
|
-
});
|
|
1332
|
-
}
|
|
1333
|
-
function deriveSourceScopes(context) {
|
|
1334
|
-
const scopes = [];
|
|
1335
|
-
const pushScope = (raw) => {
|
|
1336
|
-
if (!raw || !raw.trim()) return;
|
|
1337
|
-
if (raw.startsWith("feed:")) {
|
|
1338
|
-
if (!scopes.includes(raw)) scopes.push(raw);
|
|
1339
|
-
return;
|
|
1340
|
-
}
|
|
1341
|
-
const nb = toNotebookId$1(raw);
|
|
1342
|
-
if (nb === "notebook/defaults" || nb === "notebook/custom" || nb === "notebook/journal" || nb === "notebook/playground") {
|
|
1343
|
-
return;
|
|
1344
|
-
}
|
|
1345
|
-
if (!scopes.includes(nb)) scopes.push(nb);
|
|
1346
|
-
};
|
|
1347
|
-
if (context.note) {
|
|
1348
|
-
const feedId = context.note.provenance?.feedSourceId ?? context.note.feedSourceId;
|
|
1349
|
-
if (feedId && feedId !== "core" && feedId !== "local") {
|
|
1350
|
-
pushScope(`feed:${feedId}`);
|
|
1351
|
-
}
|
|
1352
|
-
if (context.note.provenance?.sourceNotebookId) {
|
|
1353
|
-
pushScope(context.note.provenance.sourceNotebookId);
|
|
1354
|
-
}
|
|
1355
|
-
for (const nb of notebooksOfItem(context.note)) {
|
|
1356
|
-
pushScope(nb);
|
|
1357
|
-
}
|
|
1358
|
-
const directNb = notebookOfItem(context.note);
|
|
1359
|
-
if (directNb) pushScope(directNb);
|
|
1360
|
-
}
|
|
1361
|
-
if (context.notebookId) pushScope(context.notebookId);
|
|
1362
|
-
return scopes;
|
|
1363
|
-
}
|
|
1364
|
-
async function resolveScopedPropertyCatalog(storage, context = {}) {
|
|
1365
|
-
let allOverrides = [];
|
|
1366
|
-
try {
|
|
1367
|
-
allOverrides = await storage.readonly("property_overrides").getAll();
|
|
1368
|
-
} catch {
|
|
1369
|
-
}
|
|
1370
|
-
let storedEfforts = [];
|
|
1371
|
-
let storedEquipment = [];
|
|
1372
|
-
let storedTags = [];
|
|
1373
|
-
let storedTagTypes = [];
|
|
1374
|
-
try {
|
|
1375
|
-
[storedEfforts, storedEquipment, storedTags, storedTagTypes] = await Promise.all([
|
|
1376
|
-
storage.readonly("efforts").getAll(),
|
|
1377
|
-
storage.readonly("equipment").getAll(),
|
|
1378
|
-
storage.readonly("tags").getAll(),
|
|
1379
|
-
storage.readonly("tag_types").getAll()
|
|
1380
|
-
]);
|
|
1381
|
-
} catch {
|
|
1382
|
-
}
|
|
1383
|
-
const effortsBySlug = /* @__PURE__ */ new Map();
|
|
1384
|
-
const equipmentBySlug = /* @__PURE__ */ new Map();
|
|
1385
|
-
const tagsBySlug = /* @__PURE__ */ new Map();
|
|
1386
|
-
const tagTypesByName = /* @__PURE__ */ new Map();
|
|
1387
|
-
const originByKey = /* @__PURE__ */ new Map();
|
|
1388
|
-
for (const eff of storedEfforts) {
|
|
1389
|
-
if (eff.registrySource === "bundled" && (!eff.sourceId || eff.sourceId === "core" || eff.sourceId === "efforts")) {
|
|
1390
|
-
effortsBySlug.set(eff.slug, eff);
|
|
1391
|
-
originByKey.set(`effort:${eff.slug}`, "notebook/defaults");
|
|
1392
|
-
}
|
|
1393
|
-
}
|
|
1394
|
-
for (const eq of storedEquipment) {
|
|
1395
|
-
if (eq.registrySource === "bundled" && (!eq.sourceId || eq.sourceId === "core" || eq.sourceId === "equipment")) {
|
|
1396
|
-
equipmentBySlug.set(eq.slug, eq);
|
|
1397
|
-
originByKey.set(`equipment:${eq.slug}`, "notebook/defaults");
|
|
1398
|
-
}
|
|
1399
|
-
}
|
|
1400
|
-
for (const t of storedTags) {
|
|
1401
|
-
tagsBySlug.set(t.label, t);
|
|
1402
|
-
originByKey.set(`tag:${t.label}`, "notebook/defaults");
|
|
1403
|
-
}
|
|
1404
|
-
for (const tt of storedTagTypes) {
|
|
1405
|
-
tagTypesByName.set(tt.name, tt);
|
|
1406
|
-
originByKey.set(`tag-type:${tt.name}`, "notebook/defaults");
|
|
1407
|
-
}
|
|
1408
|
-
const explicitNb = context.notebookId ? toNotebookId$1(context.notebookId) : void 0;
|
|
1409
|
-
const mode = context.mode ?? "source-first";
|
|
1410
|
-
const sourceScopes = deriveSourceScopes(context);
|
|
1411
|
-
let orderedScopes;
|
|
1412
|
-
if (explicitNb === "notebook/defaults") {
|
|
1413
|
-
orderedScopes = ["notebook/defaults"];
|
|
1414
|
-
} else if (mode === "custom-runtime" || sourceScopes.length === 0) {
|
|
1415
|
-
orderedScopes = ["notebook/defaults", ...sourceScopes, "notebook/custom"];
|
|
1416
|
-
} else {
|
|
1417
|
-
orderedScopes = ["notebook/defaults", "notebook/custom", ...sourceScopes];
|
|
1418
|
-
}
|
|
1419
|
-
if (orderedScopes.includes("notebook/custom")) {
|
|
1420
|
-
for (const eff of storedEfforts) {
|
|
1421
|
-
if (eff.registrySource === "user" && !effortsBySlug.has(eff.slug)) {
|
|
1422
|
-
effortsBySlug.set(eff.slug, eff);
|
|
1423
|
-
originByKey.set(`effort:${eff.slug}`, "notebook/custom");
|
|
1424
|
-
}
|
|
1425
|
-
}
|
|
1426
|
-
for (const eq of storedEquipment) {
|
|
1427
|
-
if (eq.registrySource === "user" && !equipmentBySlug.has(eq.slug)) {
|
|
1428
|
-
equipmentBySlug.set(eq.slug, eq);
|
|
1429
|
-
originByKey.set(`equipment:${eq.slug}`, "notebook/custom");
|
|
1430
|
-
}
|
|
1431
|
-
}
|
|
1432
|
-
}
|
|
1433
|
-
const byScope = /* @__PURE__ */ new Map();
|
|
1434
|
-
for (const ov of allOverrides) {
|
|
1435
|
-
const arr = byScope.get(ov.notebookId) ?? [];
|
|
1436
|
-
arr.push(ov);
|
|
1437
|
-
byScope.set(ov.notebookId, arr);
|
|
1438
|
-
}
|
|
1439
|
-
for (const scope of orderedScopes) {
|
|
1440
|
-
const rows = byScope.get(scope) ?? [];
|
|
1441
|
-
for (const row of rows) {
|
|
1442
|
-
const originLabel = scope.startsWith("feed:") ? scope : scope;
|
|
1443
|
-
if (row.kind === "effort") {
|
|
1444
|
-
const eff = row.payload ?? documentToEffort(row.rawContent).effort;
|
|
1445
|
-
effortsBySlug.set(row.slug, { ...eff, slug: row.slug });
|
|
1446
|
-
originByKey.set(`effort:${row.slug}`, originLabel);
|
|
1447
|
-
} else if (row.kind === "equipment") {
|
|
1448
|
-
const eq = row.payload ?? documentToEquipment(row.rawContent).equipment;
|
|
1449
|
-
equipmentBySlug.set(row.slug, { ...eq, slug: row.slug });
|
|
1450
|
-
originByKey.set(`equipment:${row.slug}`, originLabel);
|
|
1451
|
-
} else if (row.kind === "tag") {
|
|
1452
|
-
const tag = row.payload;
|
|
1453
|
-
if (tag) {
|
|
1454
|
-
tagsBySlug.set(row.slug, tag);
|
|
1455
|
-
originByKey.set(`tag:${row.slug}`, originLabel);
|
|
1456
|
-
}
|
|
1457
|
-
} else if (row.kind === "tag-type") {
|
|
1458
|
-
const tt = row.payload;
|
|
1459
|
-
if (tt) {
|
|
1460
|
-
tagTypesByName.set(row.slug, tt);
|
|
1461
|
-
originByKey.set(`tag-type:${row.slug}`, originLabel);
|
|
1462
|
-
}
|
|
1463
|
-
}
|
|
1464
|
-
}
|
|
1465
|
-
}
|
|
1466
|
-
const efforts = [...effortsBySlug.values()];
|
|
1467
|
-
const equipment = [...equipmentBySlug.values()];
|
|
1468
|
-
const tags = [...tagsBySlug.values()];
|
|
1469
|
-
const tagTypes = [...tagTypesByName.values()];
|
|
1470
|
-
const tagDefs = [
|
|
1471
|
-
...tagTypes.filter((tt) => tt.contributions && tt.contributions.length > 0).map((tt) => ({
|
|
1472
|
-
slug: `category:${tt.name}`,
|
|
1473
|
-
contributions: tt.contributions ?? []
|
|
1474
|
-
})),
|
|
1475
|
-
...tags.map((t) => ({
|
|
1476
|
-
slug: t.label,
|
|
1477
|
-
contributions: t.contributions ?? []
|
|
1478
|
-
}))
|
|
1479
|
-
];
|
|
1480
|
-
return {
|
|
1481
|
-
efforts,
|
|
1482
|
-
equipment,
|
|
1483
|
-
tags,
|
|
1484
|
-
tagTypes,
|
|
1485
|
-
referenceIndex: createReferenceIndex({ efforts, equipment }),
|
|
1486
|
-
tagIndex: createTagIndex(tagDefs),
|
|
1487
|
-
originByKey
|
|
1488
|
-
};
|
|
1489
|
-
}
|
|
1490
|
-
async function promoteReferencedOverridesToNotebook(storage, input) {
|
|
1491
|
-
const targetNb = toNotebookId$1(input.notebookId);
|
|
1492
|
-
if (isNonPublishableNotebook(targetNb)) return [];
|
|
1493
|
-
let customOverrides;
|
|
1494
|
-
let existingNbOverrides;
|
|
1495
|
-
try {
|
|
1496
|
-
[customOverrides, existingNbOverrides] = await Promise.all([
|
|
1497
|
-
storage.readonly("property_overrides").getAllFromIndex("by-notebook", "notebook/custom"),
|
|
1498
|
-
storage.readonly("property_overrides").getAllFromIndex("by-notebook", targetNb)
|
|
1499
|
-
]);
|
|
1500
|
-
} catch {
|
|
1501
|
-
return [];
|
|
1502
|
-
}
|
|
1503
|
-
const existingByKey = new Map(existingNbOverrides.map((o) => [`${o.kind}:${o.slug}`, o]));
|
|
1504
|
-
const customByKey = new Map(customOverrides.map((o) => [`${o.kind}:${o.slug}`, o]));
|
|
1505
|
-
const wantedKeys = /* @__PURE__ */ new Set();
|
|
1506
|
-
for (const s of input.effortSlugs ?? []) wantedKeys.add(`effort:${s}`);
|
|
1507
|
-
for (const s of input.equipmentSlugs ?? []) wantedKeys.add(`equipment:${s}`);
|
|
1508
|
-
for (const s of input.tagSlugs ?? []) wantedKeys.add(`tag:${s}`);
|
|
1509
|
-
const toWrite = [];
|
|
1510
|
-
const now = Date.now();
|
|
1511
|
-
for (const key of wantedKeys) {
|
|
1512
|
-
if (existingByKey.has(key)) continue;
|
|
1513
|
-
const fromCustom = customByKey.get(key);
|
|
1514
|
-
if (!fromCustom) continue;
|
|
1515
|
-
const promoted = {
|
|
1516
|
-
...fromCustom,
|
|
1517
|
-
id: makeScopedOverrideId(targetNb, fromCustom.kind, fromCustom.slug),
|
|
1518
|
-
notebookId: targetNb,
|
|
1519
|
-
updatedAt: now
|
|
1520
|
-
};
|
|
1521
|
-
toWrite.push(promoted);
|
|
1522
|
-
existingByKey.set(key, promoted);
|
|
1523
|
-
}
|
|
1524
|
-
if (toWrite.length > 0) {
|
|
1525
|
-
await storage.transaction(["property_overrides"], "readwrite", async (tx) => {
|
|
1526
|
-
await tx.readwrite("property_overrides").putMany(toWrite);
|
|
1527
|
-
});
|
|
1528
|
-
}
|
|
1529
|
-
return [...existingByKey.values()];
|
|
1530
|
-
}
|
|
1531
|
-
|
|
1532
|
-
// src/seed/runtime.ts
|
|
1533
|
-
async function seedNoteId(path) {
|
|
1534
|
-
const digest = await crypto.subtle.digest("SHA-1", new TextEncoder().encode(`${SEED_NAMESPACE}:${path}`));
|
|
1535
|
-
const bytes = new Uint8Array(digest.slice(0, 16));
|
|
1536
|
-
bytes[6] = bytes[6] & 15 | 80;
|
|
1537
|
-
bytes[8] = bytes[8] & 63 | 128;
|
|
1538
|
-
const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
1539
|
-
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
1540
|
-
}
|
|
1541
|
-
function equal(a, b) {
|
|
1542
|
-
if (Object.is(a, b)) return true;
|
|
1543
|
-
if (!a || !b || typeof a !== "object" || typeof b !== "object") return false;
|
|
1544
|
-
const ak = Object.keys(a).filter((key) => Reflect.get(a, key) !== void 0), bk = Object.keys(b).filter((key) => Reflect.get(b, key) !== void 0);
|
|
1545
|
-
return ak.length === bk.length && ak.every((key) => key in b && equal(Reflect.get(a, key), Reflect.get(b, key)));
|
|
1546
|
-
}
|
|
1547
|
-
function titleFromPath(path) {
|
|
1548
|
-
return (path.split("/").at(-1) ?? path).replace(/\.md$/, "").replace(/[-_]+/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
|
|
1549
|
-
}
|
|
1550
|
-
function refreshedBlocks(existing, rawContent, sourceRevision) {
|
|
1551
|
-
const old = existing.rawContent;
|
|
1552
|
-
let from = 0, endOld = old.length, endNew = rawContent.length;
|
|
1553
|
-
while (from < endOld && from < endNew && old[from] === rawContent[from]) from++;
|
|
1554
|
-
while (endOld > from && endNew > from && old[endOld - 1] === rawContent[endNew - 1]) {
|
|
1555
|
-
endOld--;
|
|
1556
|
-
endNew--;
|
|
1557
|
-
}
|
|
1558
|
-
const intersect = Object.values(existing.blocks).filter((b) => from < b.to && endOld > b.from);
|
|
1559
|
-
const trusted = intersect.length <= 1 ? existing.blocks : Object.fromEntries(Object.entries(existing.blocks).filter(([, b]) => !intersect.includes(b)));
|
|
1560
|
-
const mapped = mapNoteBlockChanges(trusted, [{ from, to: endOld, insert: rawContent.slice(from, endNew) }]);
|
|
1561
|
-
let ordinal = 0;
|
|
1562
|
-
return reconcileNoteBlocks(rawContent, { sourceRevision, blocks: mapped, registeredWidgets: SEED_REGISTERED_WIDGETS, createId: () => `seed:${existing.id}:r${sourceRevision}:${ordinal++}` });
|
|
1563
|
-
}
|
|
1564
|
-
async function applyDefinitionChunk(defStore, noteStore, parse, family, seedSource, incomingRank, otherCheckpoints, priorIds, rows, ids, owned, existingById, allIds) {
|
|
1565
|
-
const priorIdSet = new Set(priorIds);
|
|
1566
|
-
const maxOtherRankForNote = (noteId) => {
|
|
1567
|
-
let max = -1;
|
|
1568
|
-
for (const cp of otherCheckpoints) {
|
|
1569
|
-
if (cp.noteIds.has(noteId) && cp.rank > max) max = cp.rank;
|
|
1570
|
-
}
|
|
1571
|
-
return max;
|
|
1572
|
-
};
|
|
1573
|
-
const projections = [];
|
|
1574
|
-
const feedSourceId = seedSource;
|
|
1575
|
-
for (const [i, row] of rows.entries()) {
|
|
1576
|
-
if (!owned.has(ids[i])) continue;
|
|
1577
|
-
const parsed = parse(row.content);
|
|
1578
|
-
if (!parsed) continue;
|
|
1579
|
-
projections.push({ ...parsed, registrySource: "bundled", ownerNoteId: ids[i], sourceId: feedSourceId, sourcePath: row.path });
|
|
1580
|
-
}
|
|
1581
|
-
const prior = await defStore.getMany(projections.map((p) => p.slug));
|
|
1582
|
-
const changed = projections.filter((p, i) => {
|
|
1583
|
-
const before = prior[i];
|
|
1584
|
-
if (!before) return true;
|
|
1585
|
-
if (before.registrySource !== "bundled") return false;
|
|
1586
|
-
let beforeRank;
|
|
1587
|
-
if (before.ownerNoteId === p.ownerNoteId || before.ownerNoteId && priorIdSet.has(before.ownerNoteId) && maxOtherRankForNote(before.ownerNoteId) < incomingRank) {
|
|
1588
|
-
beforeRank = incomingRank;
|
|
1589
|
-
} else {
|
|
1590
|
-
const cpRank = before.ownerNoteId ? maxOtherRankForNote(before.ownerNoteId) : -1;
|
|
1591
|
-
beforeRank = cpRank >= 0 ? cpRank : seedPrecedenceRank(before.sourceId);
|
|
1592
|
-
}
|
|
1593
|
-
return incomingRank >= beforeRank && !equal(p, before);
|
|
1594
|
-
});
|
|
1595
|
-
if (changed.length) await defStore.putMany(changed);
|
|
1596
|
-
const wantedSlugs = new Set(projections.map((p) => p.slug));
|
|
1597
|
-
const removedBySlug = /* @__PURE__ */ new Map();
|
|
1598
|
-
for (const id of allIds) {
|
|
1599
|
-
const note = existingById.get(id);
|
|
1600
|
-
if (!note || note.seedOrigin !== "seed") continue;
|
|
1601
|
-
const slug = parse(note.rawContent)?.slug;
|
|
1602
|
-
if (slug && !wantedSlugs.has(slug)) removedBySlug.set(slug, id);
|
|
1603
|
-
}
|
|
1604
|
-
const removedSlugs = [...removedBySlug.keys()];
|
|
1605
|
-
if (removedSlugs.length) {
|
|
1606
|
-
const old = await defStore.getMany(removedSlugs);
|
|
1607
|
-
for (const [i, row] of old.entries()) {
|
|
1608
|
-
const slug = removedSlugs[i];
|
|
1609
|
-
if (!row || row.registrySource !== "bundled") continue;
|
|
1610
|
-
const removedNoteId = removedBySlug.get(slug);
|
|
1611
|
-
const isOwnedByThisSource = row.ownerNoteId === removedNoteId && (!row.sourceId || row.sourceId === seedSource || row.sourceId === family);
|
|
1612
|
-
if (!isOwnedByThisSource) continue;
|
|
1613
|
-
let restored = false;
|
|
1614
|
-
for (const cp of otherCheckpoints) {
|
|
1615
|
-
const candidateIds = cp.meta.chunks?.[family]?.noteIds ?? [];
|
|
1616
|
-
if (!candidateIds.length) continue;
|
|
1617
|
-
const candidateNotes = await noteStore.getMany(candidateIds);
|
|
1618
|
-
for (const candidateNote of candidateNotes) {
|
|
1619
|
-
if (!candidateNote || candidateNote.seedOrigin !== "seed") continue;
|
|
1620
|
-
const parsed = parse(candidateNote.rawContent);
|
|
1621
|
-
if (parsed && parsed.slug === slug) {
|
|
1622
|
-
await defStore.put({
|
|
1623
|
-
...parsed,
|
|
1624
|
-
registrySource: "bundled",
|
|
1625
|
-
ownerNoteId: candidateNote.id,
|
|
1626
|
-
sourceId: cp.sourceId,
|
|
1627
|
-
sourcePath: candidateNote.sourcePath ?? ""
|
|
1628
|
-
});
|
|
1629
|
-
restored = true;
|
|
1630
|
-
break;
|
|
1631
|
-
}
|
|
1632
|
-
}
|
|
1633
|
-
if (restored) break;
|
|
1634
|
-
}
|
|
1635
|
-
if (!restored) {
|
|
1636
|
-
await defStore.delete(slug);
|
|
1637
|
-
}
|
|
1638
|
-
}
|
|
1639
|
-
}
|
|
1640
|
-
return changed.length;
|
|
1641
|
-
}
|
|
1642
|
-
async function putChanged(store, values, keys) {
|
|
1643
|
-
if (!values.length) return;
|
|
1644
|
-
const prior = await store.getMany(keys);
|
|
1645
|
-
const changed = values.filter((value, i) => !equal(value, prior[i]));
|
|
1646
|
-
if (changed.length) await store.putMany(changed);
|
|
1647
|
-
}
|
|
1648
|
-
async function applySeedChunk(storage, write) {
|
|
1649
|
-
assertSeedManifest(write.manifest);
|
|
1650
|
-
assertSeedRows(write.rows);
|
|
1651
|
-
const result = { totalNotes: 0, totalEfforts: 0, totalEquipment: 0, totalBlocks: 0, skippedUserOwned: 0, deleted: 0, addedNotes: 0, updatedNotes: 0 };
|
|
1652
|
-
const ids = await Promise.all(write.rows.map((row) => seedNoteId(row.path)));
|
|
1653
|
-
const pagesBySlug = /* @__PURE__ */ new Map();
|
|
1654
|
-
const linkIds = /* @__PURE__ */ new Map();
|
|
1655
|
-
const tagIds = /* @__PURE__ */ new Map();
|
|
1656
|
-
for (const [i, row] of write.rows.entries()) {
|
|
1657
|
-
const slug = readFrontmatterMeta(row.content)["slug"];
|
|
1658
|
-
if (typeof slug === "string" && slug.trim()) {
|
|
1659
|
-
pagesBySlug.set(slug, await seedNoteId(`page:${slug}`));
|
|
1660
|
-
linkIds.set(ids[i], await seedNoteId(`pagenote:${slug}:${row.path}`));
|
|
1661
|
-
}
|
|
1662
|
-
for (const { label } of extractTypedTags(row.content)) {
|
|
1663
|
-
if (!tagIds.has(label)) tagIds.set(label, await seedNoteId(`tag:${label}`));
|
|
1664
|
-
}
|
|
1665
|
-
}
|
|
1666
|
-
return storage.transaction(["notes", "block_revisions", "block_index", "block_efforts", "block_equipment", "page", "page_notes", "tags", "note_tags", "efforts", "equipment", "property_overrides", "meta", "sessions", "events"], "readwrite", async (tx) => {
|
|
1667
|
-
const metaStore = tx.readwrite("meta");
|
|
1668
|
-
const userDeleted = /* @__PURE__ */ new Set();
|
|
1669
|
-
for (const row of await metaStore.getAll()) {
|
|
1670
|
-
const suppressed = userDeletedSeedNoteId(row?.key);
|
|
1671
|
-
if (suppressed !== void 0) userDeleted.add(suppressed);
|
|
1672
|
-
}
|
|
1673
|
-
const actualMeta = await metaStore.get(write.meta.key);
|
|
1674
|
-
if (!equal(actualMeta, write.expectedMeta)) throw new Error("Seed checkpoint changed during import");
|
|
1675
|
-
if (write.meta.schema !== SEED_SCHEMA || write.manifest.schema !== SEED_SCHEMA) throw new Error("Incompatible seed schema; recreate artifacts");
|
|
1676
|
-
const noteStore = tx.readwrite("notes");
|
|
1677
|
-
const priorIds = write.chunkId ? write.expectedMeta?.chunks[write.chunkId]?.noteIds ?? [] : [];
|
|
1678
|
-
const declared = new Set((write.chunkId ? write.meta.chunks[write.chunkId]?.noteIds : void 0) ?? ids);
|
|
1679
|
-
const goneIds = priorIds.filter((id) => !declared.has(id));
|
|
1680
|
-
const allIds = [.../* @__PURE__ */ new Set([...ids, ...goneIds])];
|
|
1681
|
-
const stored = await noteStore.getMany(allIds);
|
|
1682
|
-
const existingById = new Map(allIds.map((id, i) => [id, stored[i]]));
|
|
1683
|
-
const seedSource = write.meta.key.startsWith("seed:") ? write.meta.key.slice(5) : write.meta.key;
|
|
1684
|
-
const feedSourceId = feedIdOfMetaKey(write.meta.key);
|
|
1685
|
-
const incomingRank = seedPrecedenceRank(write.meta.key, write.meta.tier);
|
|
1686
|
-
const otherCheckpoints = [];
|
|
1687
|
-
for (const row of await metaStore.getAll()) {
|
|
1688
|
-
const meta = row;
|
|
1689
|
-
if (!meta || typeof meta.key !== "string" || !meta.key.startsWith("seed:") || meta.key === write.meta.key) continue;
|
|
1690
|
-
const noteIds = /* @__PURE__ */ new Set();
|
|
1691
|
-
for (const chunk of Object.values(meta.chunks ?? {})) {
|
|
1692
|
-
for (const noteId of chunk.noteIds ?? []) noteIds.add(noteId);
|
|
1693
|
-
}
|
|
1694
|
-
otherCheckpoints.push({
|
|
1695
|
-
key: meta.key,
|
|
1696
|
-
sourceId: meta.key.slice(5),
|
|
1697
|
-
rank: seedPrecedenceRank(meta.key, meta.tier),
|
|
1698
|
-
meta,
|
|
1699
|
-
noteIds
|
|
1700
|
-
});
|
|
1701
|
-
}
|
|
1702
|
-
otherCheckpoints.sort((a, b) => b.rank - a.rank);
|
|
1703
|
-
const maxOtherRankForNote = (noteId) => {
|
|
1704
|
-
let max = -1;
|
|
1705
|
-
for (const cp of otherCheckpoints) {
|
|
1706
|
-
if (cp.noteIds.has(noteId) && cp.rank > max) max = cp.rank;
|
|
1707
|
-
}
|
|
1708
|
-
return max;
|
|
1709
|
-
};
|
|
1710
|
-
const ownedIds = allIds.filter((id) => {
|
|
1711
|
-
if (userDeleted.has(id)) return false;
|
|
1712
|
-
const note = existingById.get(id);
|
|
1713
|
-
if (!note) return declared.has(id);
|
|
1714
|
-
if (note.seedOrigin !== "seed") return false;
|
|
1715
|
-
const otherRank = maxOtherRankForNote(id);
|
|
1716
|
-
if (declared.has(id)) return incomingRank >= otherRank;
|
|
1717
|
-
return otherRank < 0 && note.seedChunkId === write.chunkId;
|
|
1718
|
-
});
|
|
1719
|
-
const owned = new Set(ownedIds);
|
|
1720
|
-
const revisionStore = tx.readwrite("block_revisions");
|
|
1721
|
-
const historyIds = ids.filter((id, i) => owned.has(id) && existingById.get(id)?.rawContent !== write.rows[i].content);
|
|
1722
|
-
const histories = await revisionStore.getAllFromIndexMany("by-note", historyIds);
|
|
1723
|
-
const history = new Map(historyIds.map((id, i) => [id, histories[i]]));
|
|
1724
|
-
const indexStore = tx.readwrite("block_index"), effortLinks = tx.readwrite("block_efforts"), equipmentLinks = tx.readwrite("block_equipment");
|
|
1725
|
-
const tagLinks = tx.readwrite("note_tags"), pageLinks = tx.readwrite("page_notes");
|
|
1726
|
-
const currentIndexes = await indexStore.getAllFromIndexMany("by-note", ownedIds);
|
|
1727
|
-
const currentEfforts = await effortLinks.getAllFromIndexMany("by-note", ownedIds);
|
|
1728
|
-
const currentEquipment = await equipmentLinks.getAllFromIndexMany("by-note", ownedIds);
|
|
1729
|
-
const currentTags = await tagLinks.getAllFromIndexMany("by-note", ownedIds);
|
|
1730
|
-
const currentPages = await pageLinks.getAllFromIndexMany("by-note", ownedIds);
|
|
1731
|
-
const slot = new Map(ownedIds.map((id, i) => [id, i]));
|
|
1732
|
-
const tagsStore = tx.readwrite("tags");
|
|
1733
|
-
const labels = [...tagIds.keys()];
|
|
1734
|
-
const matches = await tagsStore.getAllFromIndexMany("by-label", labels);
|
|
1735
|
-
const tagsByLabel = new Map(labels.map((label, i) => [label, matches[i][0]]));
|
|
1736
|
-
const changedTags = [], changedNotes = [], revisions = [], pages = [], pageNotes = [], noteTags = [];
|
|
1737
|
-
const blocks = [], blockEfforts = [], blockEquipment = [];
|
|
1738
|
-
const sessionStore = tx.readwrite("sessions"), eventStore = tx.readwrite("events");
|
|
1739
|
-
const telemetrySessionIds = write.rows.flatMap((row) => row.telemetry?.sessions.map((session) => session.id) ?? []);
|
|
1740
|
-
const storedTelemetrySessions = await sessionStore.getMany(telemetrySessionIds);
|
|
1741
|
-
const existingTelemetrySessions = new Map(telemetrySessionIds.map((sessionId, i) => [sessionId, storedTelemetrySessions[i]]));
|
|
1742
|
-
const sessions = [], events = [];
|
|
1743
|
-
for (const [i, row] of write.rows.entries()) {
|
|
1744
|
-
const id = ids[i], existing = existingById.get(id);
|
|
1745
|
-
if (!owned.has(id)) {
|
|
1746
|
-
if (existing && existing.seedOrigin !== "seed") result.skippedUserOwned++;
|
|
1747
|
-
continue;
|
|
1748
|
-
}
|
|
1749
|
-
if (!existing) result.addedNotes++;
|
|
1750
|
-
else if (existing.rawContent !== row.content) result.updatedNotes++;
|
|
1751
|
-
validateNoteBlocks(row.content, row.blocks, 1, { registeredWidgets: SEED_REGISTERED_WIDGETS });
|
|
1752
|
-
const sourceRevision = existing ? existing.sourceRevision + (existing.rawContent === row.content ? 0 : 1) : 1;
|
|
1753
|
-
let ordinal = 0;
|
|
1754
|
-
const retainedHistory = history.get(id) ?? [];
|
|
1755
|
-
const map = !existing ? retainedHistory.length ? reconcileNoteBlocks(row.content, { sourceRevision, registeredWidgets: SEED_REGISTERED_WIDGETS, createId: () => `seed:${id}:new${retainedHistory.length}:${ordinal++}` }) : structuredClone(row.blocks) : existing.rawContent === row.content ? structuredClone(existing.blocks) : refreshedBlocks(existing, row.content, sourceRevision);
|
|
1756
|
-
for (const block of Object.values(map)) {
|
|
1757
|
-
const saved = (history.get(id) ?? []).filter((r) => r.blockId === block.id).sort((a, b) => b.version - a.version)[0];
|
|
1758
|
-
const source = row.content.slice(block.from, block.to);
|
|
1759
|
-
if (existing?.rawContent === row.content) continue;
|
|
1760
|
-
const same = saved && saved.kind === block.kind && saved.rawContent === source && saved.dialect === block.dialect && saved.sport === block.sport;
|
|
1761
|
-
block.version = !existing ? 1 : same ? saved.version : (saved?.version ?? 0) + 1;
|
|
1762
|
-
if (!existing || !same) revisions.push({ noteId: id, blockId: block.id, version: block.version, kind: block.kind, rawContent: source, savedAt: write.meta.importedAt, ...block.dialect ? { dialect: block.dialect } : {}, ...block.sport ? { sport: block.sport } : {} });
|
|
1763
|
-
}
|
|
1764
|
-
validateNoteBlocks(row.content, map, sourceRevision, { registeredWidgets: SEED_REGISTERED_WIDGETS });
|
|
1765
|
-
const fm = readFrontmatterMeta(row.content);
|
|
1766
|
-
const title = typeof fm["title"] === "string" && fm["title"].trim() ? fm["title"].trim() : titleFromPath(row.path);
|
|
1767
|
-
const sourceId = write.chunkId ? seedNoteSourceId(row.path, row.content, write.chunkId) : void 0;
|
|
1768
|
-
if (!sourceId) throw new Error(`Unknown seed source family ${write.chunkId}`);
|
|
1769
|
-
const dateMatch = typeof fm["date"] === "string" ? fm["date"].match(/^(\d{4})-(\d{2})-(\d{2})$/) : null;
|
|
1770
|
-
let date;
|
|
1771
|
-
if (dateMatch) {
|
|
1772
|
-
const ts = Date.parse(`${fm["date"]}T12:00:00Z`);
|
|
1773
|
-
const real = Number.isFinite(ts) && new Date(ts).getUTCMonth() === Number(dateMatch[2]) - 1 && new Date(ts).getUTCDate() === Number(dateMatch[3]);
|
|
1774
|
-
if (!real) throw new Error(`invalid frontmatter date '${fm["date"]}' in '${row.path}' \u2014 expected a real calendar day (YYYY-MM-DD)`);
|
|
1775
|
-
date = ts;
|
|
1776
|
-
}
|
|
1777
|
-
const seedCommit = row.commit ?? write.manifest.commit;
|
|
1778
|
-
const note = { ...existing, id, title, rawContent: row.content, sourceRevision, blocks: map, createdAt: write.manifest.version, ...date === void 0 ? {} : { date }, type: write.chunkId === DASHBOARDS_CHUNK_ID ? "dashboard" : "note", sourceId, seedOrigin: "seed", seedVersion: write.manifest.version, seedChunkId: write.chunkId ?? void 0, feedOrigin: "feed", feedSourceId, sourcePath: row.path, ...seedCommit ? { seedCommit } : {} };
|
|
1779
|
-
if (date === void 0) delete note.date;
|
|
1780
|
-
if (!equal(note, existing)) changedNotes.push(note);
|
|
1781
|
-
const byRange = new Map(Object.values(map).map((b) => [`${b.from}:${b.to}`, b]));
|
|
1782
|
-
const compiledById = new Map(row.blockIndex.map((b) => [b.blockId, b]));
|
|
1783
|
-
const remap = /* @__PURE__ */ new Map();
|
|
1784
|
-
for (const compiled of row.blockIndex) {
|
|
1785
|
-
const block = byRange.get(`${compiled.from}:${compiled.to}`);
|
|
1786
|
-
if (!block || block.kind !== compiled.dataType) throw new Error("Orphan seed projection");
|
|
1787
|
-
remap.set(compiled.blockId, block.id);
|
|
1788
|
-
const projection = { ...compiled, id: `${id}:${block.id}`, noteId: id, blockId: block.id, blockVersion: block.version, sourceRevision, noteTitle: title, sourceId, sourcePath: row.path, rawContent: row.content.slice(block.from, block.to) };
|
|
1789
|
-
const prior = currentIndexes[slot.get(id)].find((b) => b.id === projection.id);
|
|
1790
|
-
if (!prior || prior.isStatic === true) blocks.push(projection);
|
|
1791
|
-
}
|
|
1792
|
-
const resolvedSessions = /* @__PURE__ */ new Map();
|
|
1793
|
-
for (const compiled of row.telemetry?.sessions ?? []) {
|
|
1794
|
-
if (compiledById.get(compiled.blockId)?.dataType !== "wod") throw new Error("Orphan seed session pin");
|
|
1795
|
-
const prior = existingTelemetrySessions.get(compiled.id);
|
|
1796
|
-
if (prior && prior.noteId !== id) throw new Error(`Seed session ${compiled.id} belongs to another note`);
|
|
1797
|
-
const blockId = prior?.blockId ?? remap.get(compiled.blockId);
|
|
1798
|
-
if (!blockId) throw new Error("Orphan seed session pin");
|
|
1799
|
-
const block = map[blockId];
|
|
1800
|
-
if (!prior && !block) throw new Error("Orphan seed session pin");
|
|
1801
|
-
const session = {
|
|
1802
|
-
...compiled,
|
|
1803
|
-
noteId: id,
|
|
1804
|
-
blockId,
|
|
1805
|
-
blockVersion: prior?.blockVersion ?? block.version,
|
|
1806
|
-
blockContentId: prior?.blockContentId ?? compiledById.get(compiled.blockId)?.blockContentId
|
|
1807
|
-
};
|
|
1808
|
-
sessions.push(session);
|
|
1809
|
-
resolvedSessions.set(session.id, session);
|
|
1810
|
-
}
|
|
1811
|
-
for (const compiled of row.telemetry?.events ?? []) {
|
|
1812
|
-
const session = resolvedSessions.get(compiled.resultId);
|
|
1813
|
-
if (!session) throw new Error("Orphan seed event result");
|
|
1814
|
-
events.push({
|
|
1815
|
-
...compiled,
|
|
1816
|
-
noteId: id,
|
|
1817
|
-
blockId: session.blockId,
|
|
1818
|
-
blockVersion: session.blockVersion,
|
|
1819
|
-
blockContentId: session.blockContentId
|
|
1820
|
-
});
|
|
1821
|
-
}
|
|
1822
|
-
for (const compiled of row.blockEfforts) {
|
|
1823
|
-
const blockId = remap.get(compiled.blockId);
|
|
1824
|
-
if (!blockId || compiledById.get(compiled.blockId)?.dataType !== "wod") throw new Error("Orphan seed effort link");
|
|
1825
|
-
const link = { ...compiled, id: `${id}:${blockId}:${compiled.effortSlug}`, noteId: id, blockId, sourcePath: row.path };
|
|
1826
|
-
const prior = currentEfforts[slot.get(id)].find((b) => b.id === link.id);
|
|
1827
|
-
if (!prior || prior.isStatic === true) blockEfforts.push(prior ? { ...link, createdAt: prior.createdAt } : link);
|
|
1828
|
-
}
|
|
1829
|
-
for (const compiled of row.blockEquipment) {
|
|
1830
|
-
const blockId = remap.get(compiled.blockId);
|
|
1831
|
-
if (!blockId || compiledById.get(compiled.blockId)?.dataType !== "wod") throw new Error("Orphan seed equipment link");
|
|
1832
|
-
const link = { ...compiled, id: `${id}:${blockId}:${compiled.equipmentSlug}`, noteId: id, blockId, sourcePath: row.path };
|
|
1833
|
-
const prior = currentEquipment[slot.get(id)].find((b) => b.id === link.id);
|
|
1834
|
-
if (!prior || prior.isStatic === true) blockEquipment.push(prior ? { ...link, createdAt: prior.createdAt } : link);
|
|
1835
|
-
}
|
|
1836
|
-
const n = slot.get(id);
|
|
1837
|
-
const wantedTags = /* @__PURE__ */ new Set();
|
|
1838
|
-
for (const item of extractTypedTags(row.content)) {
|
|
1839
|
-
let tag = tagsByLabel.get(item.label);
|
|
1840
|
-
if (!tag) {
|
|
1841
|
-
tag = { id: tagIds.get(item.label), label: item.label, type: item.type, createdAt: write.meta.importedAt };
|
|
1842
|
-
changedTags.push(tag);
|
|
1843
|
-
tagsByLabel.set(item.label, tag);
|
|
1844
|
-
} else if (item.type && !tag.type) {
|
|
1845
|
-
tag = { ...tag, type: item.type };
|
|
1846
|
-
changedTags.push(tag);
|
|
1847
|
-
tagsByLabel.set(item.label, tag);
|
|
1848
|
-
}
|
|
1849
|
-
if (wantedTags.has(tag.id)) continue;
|
|
1850
|
-
wantedTags.add(tag.id);
|
|
1851
|
-
const link = currentTags[n].find((l) => l.tagId === tag.id);
|
|
1852
|
-
if (!link) noteTags.push({ id: `${id}:${tag.id}`, noteId: id, tagId: tag.id });
|
|
1853
|
-
}
|
|
1854
|
-
for (const link of currentTags[n]) if (!wantedTags.has(link.tagId)) await tagLinks.delete(link.id);
|
|
1855
|
-
const slug = fm["slug"];
|
|
1856
|
-
if (typeof slug === "string" && pagesBySlug.has(slug)) {
|
|
1857
|
-
const pageId = pagesBySlug.get(slug);
|
|
1858
|
-
pages.push({ id: pageId, slug, title: titleFromPath(row.path), createdAt: write.manifest.version });
|
|
1859
|
-
pageNotes.push({ id: linkIds.get(id), pageId, noteId: id, createdAt: write.manifest.version });
|
|
1860
|
-
}
|
|
1861
|
-
result.totalNotes++;
|
|
1862
|
-
result.totalBlocks += Object.keys(map).length;
|
|
1863
|
-
}
|
|
1864
|
-
const wantedBlocks = new Set(blocks.map((b) => b.id)), wantedEfforts = new Set(blockEfforts.map((b) => b.id)), wantedEquipment = new Set(blockEquipment.map((b) => b.id));
|
|
1865
|
-
for (const rows of currentIndexes) for (const row of rows) if (row.isStatic === true && !wantedBlocks.has(row.id)) await indexStore.delete(row.id);
|
|
1866
|
-
for (const rows of currentEfforts) for (const row of rows) if (row.isStatic === true && !wantedEfforts.has(row.id)) await effortLinks.delete(row.id);
|
|
1867
|
-
for (const rows of currentEquipment) for (const row of rows) if (row.isStatic === true && !wantedEquipment.has(row.id)) await equipmentLinks.delete(row.id);
|
|
1868
|
-
for (const id of goneIds) {
|
|
1869
|
-
if (!owned.has(id) || !existingById.get(id)) continue;
|
|
1870
|
-
const n = slot.get(id);
|
|
1871
|
-
await noteStore.delete(id);
|
|
1872
|
-
for (const link of currentTags[n]) await tagLinks.delete(link.id);
|
|
1873
|
-
for (const link of currentPages[n]) await pageLinks.delete(link.id);
|
|
1874
|
-
result.deleted++;
|
|
1875
|
-
}
|
|
1876
|
-
const recordSeedPropertyOverrides = async (kind, parse) => {
|
|
1877
|
-
let overrideStore;
|
|
1878
|
-
try {
|
|
1879
|
-
overrideStore = tx.readwrite("property_overrides");
|
|
1880
|
-
} catch {
|
|
1881
|
-
return;
|
|
1882
|
-
}
|
|
1883
|
-
const scopes = feedSourceId === "core" ? ["notebook/defaults"] : [
|
|
1884
|
-
`feed:${feedSourceId}`,
|
|
1885
|
-
...write.manifest.chunks.filter((c) => c.id.startsWith("notebook.")).map((c) => `notebook/${notebookSlugForChunkId(c.id)}`)
|
|
1886
|
-
];
|
|
1887
|
-
const wantedIds = /* @__PURE__ */ new Set();
|
|
1888
|
-
const toPut = [];
|
|
1889
|
-
for (const [idx, row] of write.rows.entries()) {
|
|
1890
|
-
const parsed = parse(row.content);
|
|
1891
|
-
if (!parsed) continue;
|
|
1892
|
-
for (const scope of scopes) {
|
|
1893
|
-
const ovId = makeScopedOverrideId(scope, kind, parsed.slug);
|
|
1894
|
-
wantedIds.add(ovId);
|
|
1895
|
-
toPut.push({
|
|
1896
|
-
id: ovId,
|
|
1897
|
-
notebookId: scope,
|
|
1898
|
-
kind,
|
|
1899
|
-
slug: parsed.slug,
|
|
1900
|
-
label: parsed.label,
|
|
1901
|
-
ownerNoteId: ids[idx],
|
|
1902
|
-
rawContent: row.content,
|
|
1903
|
-
payload: parsed,
|
|
1904
|
-
seedOrigin: "seed",
|
|
1905
|
-
feedSourceId,
|
|
1906
|
-
updatedAt: write.meta.importedAt
|
|
1907
|
-
});
|
|
1908
|
-
}
|
|
1909
|
-
}
|
|
1910
|
-
if (toPut.length > 0) await overrideStore.putMany(toPut);
|
|
1911
|
-
const existingAll = await overrideStore.getAll();
|
|
1912
|
-
for (const existingOv of existingAll) {
|
|
1913
|
-
if (existingOv.seedOrigin === "seed" && existingOv.feedSourceId === feedSourceId && existingOv.kind === kind && !wantedIds.has(existingOv.id)) {
|
|
1914
|
-
await overrideStore.delete(existingOv.id);
|
|
1915
|
-
}
|
|
1916
|
-
}
|
|
1917
|
-
};
|
|
1918
|
-
if (write.chunkId === EFFORTS_CHUNK_ID) {
|
|
1919
|
-
result.totalEfforts = await applyDefinitionChunk(tx.readwrite("efforts"), noteStore, parseEffortFile, "efforts", seedSource, incomingRank, otherCheckpoints, priorIds, write.rows, ids, owned, existingById, allIds);
|
|
1920
|
-
await recordSeedPropertyOverrides("effort", parseEffortFile);
|
|
1921
|
-
}
|
|
1922
|
-
if (write.chunkId === EQUIPMENT_CHUNK_ID) {
|
|
1923
|
-
result.totalEquipment = await applyDefinitionChunk(tx.readwrite("equipment"), noteStore, parseEquipmentFile, "equipment", seedSource, incomingRank, otherCheckpoints, priorIds, write.rows, ids, owned, existingById, allIds);
|
|
1924
|
-
await recordSeedPropertyOverrides("equipment", parseEquipmentFile);
|
|
1925
|
-
}
|
|
1926
|
-
if (changedNotes.length) await noteStore.putMany(changedNotes);
|
|
1927
|
-
if (revisions.length) await revisionStore.putMany(revisions);
|
|
1928
|
-
await putChanged(indexStore, blocks, blocks.map((b) => b.id));
|
|
1929
|
-
await putChanged(effortLinks, blockEfforts, blockEfforts.map((b) => b.id));
|
|
1930
|
-
await putChanged(equipmentLinks, blockEquipment, blockEquipment.map((b) => b.id));
|
|
1931
|
-
await putChanged(sessionStore, sessions, sessions.map((session) => session.id));
|
|
1932
|
-
await putChanged(eventStore, events, events.map((event) => event.id));
|
|
1933
|
-
if (changedTags.length) await tagsStore.putMany([...new Map(changedTags.map((t) => [t.id, t])).values()]);
|
|
1934
|
-
if (noteTags.length) await tagLinks.putMany(noteTags);
|
|
1935
|
-
await putChanged(tx.readwrite("page"), pages, pages.map((p) => p.id));
|
|
1936
|
-
await putChanged(pageLinks, pageNotes, pageNotes.map((p) => p.id));
|
|
1937
|
-
await metaStore.put(write.meta);
|
|
1938
|
-
return result;
|
|
1939
|
-
});
|
|
1940
|
-
}
|
|
1941
|
-
function owningFeed(claims, note) {
|
|
1942
|
-
const byChunk = note.seedChunkId ? claims.filter((claim) => claim.chunkId === note.seedChunkId) : [];
|
|
1943
|
-
const pool = byChunk.length > 0 ? byChunk : claims;
|
|
1944
|
-
return [...pool].sort((a, b) => b.rank - a.rank || (a.key < b.key ? -1 : a.key > b.key ? 1 : 0))[0];
|
|
1945
|
-
}
|
|
1946
|
-
async function backfillFeedProvenance(storage) {
|
|
1947
|
-
return await storage.transaction(["meta", "notes", "block_index"], "readwrite", async (tx) => {
|
|
1948
|
-
const metaStore = tx.readwrite("meta");
|
|
1949
|
-
const claims = /* @__PURE__ */ new Map();
|
|
1950
|
-
for (const row of await metaStore.getAll()) {
|
|
1951
|
-
const meta = row;
|
|
1952
|
-
if (!meta || typeof meta.key !== "string" || !meta.key.startsWith("seed:")) continue;
|
|
1953
|
-
const sourceId = meta.key.slice("seed:".length);
|
|
1954
|
-
const rank = seedPrecedenceRank(meta.key, meta.tier);
|
|
1955
|
-
for (const [chunkId, chunk] of Object.entries(meta.chunks ?? {})) {
|
|
1956
|
-
for (const noteId of chunk.noteIds ?? []) {
|
|
1957
|
-
const list = claims.get(noteId) ?? [];
|
|
1958
|
-
list.push({ sourceId, chunkId, rank, key: meta.key });
|
|
1959
|
-
claims.set(noteId, list);
|
|
1960
|
-
}
|
|
1961
|
-
}
|
|
1962
|
-
}
|
|
1963
|
-
if (claims.size === 0) return 0;
|
|
1964
|
-
const noteStore = tx.readwrite("notes");
|
|
1965
|
-
const indexStore = tx.readwrite("block_index");
|
|
1966
|
-
const ids = [...claims.keys()];
|
|
1967
|
-
const stored = await noteStore.getMany(ids);
|
|
1968
|
-
const repaired = [];
|
|
1969
|
-
for (let i = 0; i < ids.length; i++) {
|
|
1970
|
-
const id = ids[i];
|
|
1971
|
-
const note = stored[i];
|
|
1972
|
-
if (!note || note.seedOrigin !== "seed" || note.feedSourceId) continue;
|
|
1973
|
-
const owner = owningFeed(claims.get(id), note);
|
|
1974
|
-
const sourceRevision = note.sourceRevision + 1;
|
|
1975
|
-
const blocks = Object.fromEntries(
|
|
1976
|
-
Object.entries(note.blocks).map(([blockId, block]) => [blockId, { ...block, sourceRevision }])
|
|
1977
|
-
);
|
|
1978
|
-
await noteStore.put({ ...note, blocks, sourceRevision, feedOrigin: "feed", feedSourceId: owner.sourceId });
|
|
1979
|
-
repaired.push({ id, sourceRevision });
|
|
1980
|
-
}
|
|
1981
|
-
if (repaired.length > 0) {
|
|
1982
|
-
const revisions = new Map(repaired.map((entry) => [entry.id, entry.sourceRevision]));
|
|
1983
|
-
const projections = await indexStore.getAllFromIndexMany("by-note", repaired.map((entry) => entry.id));
|
|
1984
|
-
const changed = projections.flatMap((rows) => rows.flatMap((row) => {
|
|
1985
|
-
const revision = revisions.get(row.noteId);
|
|
1986
|
-
return revision !== void 0 && row.sourceRevision !== revision ? [{ ...row, sourceRevision: revision }] : [];
|
|
1987
|
-
}));
|
|
1988
|
-
if (changed.length > 0) await indexStore.putMany(changed);
|
|
1989
|
-
}
|
|
1990
|
-
return repaired.length;
|
|
1991
|
-
});
|
|
1992
|
-
}
|
|
1993
|
-
async function migrateNotebookVocabulary(storage) {
|
|
1994
|
-
return await storage.transaction(["meta", "notes", "block_index", "block_efforts", "block_equipment"], "readwrite", async (tx) => {
|
|
1995
|
-
let migrated = 0;
|
|
1996
|
-
const metaStore = tx.readwrite("meta");
|
|
1997
|
-
for (const row of await metaStore.getAll()) {
|
|
1998
|
-
const meta = row;
|
|
1999
|
-
if (!meta || typeof meta.key !== "string" || !meta.key.startsWith("seed:")) continue;
|
|
2000
|
-
const chunks = meta.chunks ?? {};
|
|
2001
|
-
let renamed = false;
|
|
2002
|
-
const next = {};
|
|
2003
|
-
for (const [chunkId, chunk] of Object.entries(chunks)) {
|
|
2004
|
-
const id = migrateLegacyChunkId(chunkId);
|
|
2005
|
-
if (id !== chunkId) renamed = true;
|
|
2006
|
-
next[id] = next[id] && next[id] !== chunk ? { ...next[id], noteIds: [.../* @__PURE__ */ new Set([...next[id].noteIds ?? [], ...chunk.noteIds ?? []])] } : chunk;
|
|
2007
|
-
}
|
|
2008
|
-
if (renamed) {
|
|
2009
|
-
await metaStore.put({ ...meta, chunks: next });
|
|
2010
|
-
migrated++;
|
|
2011
|
-
}
|
|
2012
|
-
}
|
|
2013
|
-
for (const storeName of ["notes", "block_index", "block_efforts", "block_equipment"]) {
|
|
2014
|
-
const store = tx.readwrite(storeName);
|
|
2015
|
-
for (const row of await store.getAll()) {
|
|
2016
|
-
const record = row;
|
|
2017
|
-
if (!hasLegacyIdentity(record)) continue;
|
|
2018
|
-
await store.put(migrateLegacyRow(record));
|
|
2019
|
-
migrated++;
|
|
2020
|
-
}
|
|
2021
|
-
}
|
|
2022
|
-
return migrated;
|
|
2023
|
-
});
|
|
2024
|
-
}
|
|
2025
|
-
|
|
2026
|
-
// src/feed/qr.ts
|
|
2027
|
-
var APP_ORIGIN = "https://wod.wiki";
|
|
2028
|
-
var QR_SCRIPT_ID = "wod-feed-qr";
|
|
2029
|
-
function qrInlineScript(appOrigin = APP_ORIGIN) {
|
|
2030
|
-
return SCRIPT.replace("__APP_ORIGIN__", appOrigin);
|
|
2031
|
-
}
|
|
2032
|
-
var SCRIPT = `(function () {
|
|
2033
|
-
'use strict';
|
|
2034
|
-
|
|
2035
|
-
var APP_ORIGIN = '__APP_ORIGIN__';
|
|
2036
|
-
|
|
2037
|
-
// Error correction level M: [ecc codewords per block, block count] for
|
|
2038
|
-
// versions 1..20.
|
|
2039
|
-
var ECC_TABLE = [
|
|
2040
|
-
[10, 1], [16, 1], [26, 1], [18, 2], [24, 2], [16, 4], [18, 4], [22, 4],
|
|
2041
|
-
[22, 5], [26, 5], [30, 5], [22, 8], [22, 9], [24, 9], [24, 10],
|
|
2042
|
-
[28, 10], [28, 11], [26, 13], [26, 14], [22, 18]
|
|
2043
|
-
];
|
|
2044
|
-
var MAX_VERSION = ECC_TABLE.length;
|
|
2045
|
-
var MODE_BYTE = 4;
|
|
2046
|
-
var FORMAT_BITS_M = 0;
|
|
2047
|
-
|
|
2048
|
-
// \u2500\u2500 GF(256) arithmetic (Reed-Solomon) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
2049
|
-
|
|
2050
|
-
function gfMul(x, y) {
|
|
2051
|
-
var z = 0;
|
|
2052
|
-
for (var i = 7; i >= 0; i--) {
|
|
2053
|
-
z = (z << 1) ^ ((z >>> 7) * 0x11d);
|
|
2054
|
-
z ^= ((y >>> i) & 1) * x;
|
|
2055
|
-
}
|
|
2056
|
-
return z & 0xff;
|
|
2057
|
-
}
|
|
2058
|
-
|
|
2059
|
-
function rsDivisor(degree) {
|
|
2060
|
-
var result = [];
|
|
2061
|
-
for (var i = 0; i < degree - 1; i++) result.push(0);
|
|
2062
|
-
result.push(1);
|
|
2063
|
-
var root = 1;
|
|
2064
|
-
for (var i = 0; i < degree; i++) {
|
|
2065
|
-
for (var j = 0; j < result.length; j++) {
|
|
2066
|
-
result[j] = gfMul(result[j], root);
|
|
2067
|
-
if (j + 1 < result.length) result[j] ^= result[j + 1];
|
|
2068
|
-
}
|
|
2069
|
-
root = gfMul(root, 0x02);
|
|
2070
|
-
}
|
|
2071
|
-
return result;
|
|
2072
|
-
}
|
|
2073
|
-
|
|
2074
|
-
function rsRemainder(data, divisor) {
|
|
2075
|
-
var result = divisor.map(function () { return 0; });
|
|
2076
|
-
for (var i = 0; i < data.length; i++) {
|
|
2077
|
-
var factor = data[i] ^ (result.shift() & 0xff);
|
|
2078
|
-
result.push(0);
|
|
2079
|
-
for (var j = 0; j < divisor.length; j++) result[j] ^= gfMul(divisor[j], factor);
|
|
2080
|
-
}
|
|
2081
|
-
return result;
|
|
2082
|
-
}
|
|
2083
|
-
|
|
2084
|
-
// \u2500\u2500 Version geometry \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
2085
|
-
|
|
2086
|
-
function numRawDataModules(ver) {
|
|
2087
|
-
var result = (16 * ver + 128) * ver + 64;
|
|
2088
|
-
if (ver >= 2) {
|
|
2089
|
-
var numAlign = Math.floor(ver / 7) + 2;
|
|
2090
|
-
result -= (25 * numAlign - 10) * numAlign - 55;
|
|
2091
|
-
if (ver >= 7) result -= 36;
|
|
2092
|
-
}
|
|
2093
|
-
return result;
|
|
2094
|
-
}
|
|
2095
|
-
|
|
2096
|
-
function numDataCodewords(ver) {
|
|
2097
|
-
var t = ECC_TABLE[ver - 1];
|
|
2098
|
-
return Math.floor(numRawDataModules(ver) / 8) - t[0] * t[1];
|
|
2099
|
-
}
|
|
2100
|
-
|
|
2101
|
-
function alignmentPositions(ver) {
|
|
2102
|
-
if (ver === 1) return [];
|
|
2103
|
-
var numAlign = Math.floor(ver / 7) + 2;
|
|
2104
|
-
var step = Math.ceil((ver * 4 + 4) / (numAlign * 2 - 2)) * 2;
|
|
2105
|
-
var size = ver * 4 + 17;
|
|
2106
|
-
var result = [6];
|
|
2107
|
-
for (var pos = size - 7; result.length < numAlign; pos -= step) result.splice(1, 0, pos);
|
|
2108
|
-
return result;
|
|
2109
|
-
}
|
|
2110
|
-
|
|
2111
|
-
// \u2500\u2500 Bit stream \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
2112
|
-
|
|
2113
|
-
function utf8Bytes(text) {
|
|
2114
|
-
if (typeof TextEncoder !== 'undefined') return Array.from(new TextEncoder().encode(text));
|
|
2115
|
-
var out = [];
|
|
2116
|
-
for (var i = 0; i < text.length; i++) {
|
|
2117
|
-
var c = text.charCodeAt(i);
|
|
2118
|
-
if (c < 0x80) out.push(c);
|
|
2119
|
-
else if (c < 0x800) out.push(0xc0 | (c >> 6), 0x80 | (c & 0x3f));
|
|
2120
|
-
else out.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f));
|
|
2121
|
-
}
|
|
2122
|
-
return out;
|
|
2123
|
-
}
|
|
2124
|
-
|
|
2125
|
-
function buildCodewords(text, ver) {
|
|
2126
|
-
var bytes = utf8Bytes(text);
|
|
2127
|
-
var ccBits = ver <= 9 ? 8 : 16;
|
|
2128
|
-
var bits = [];
|
|
2129
|
-
function push(value, len) {
|
|
2130
|
-
for (var i = len - 1; i >= 0; i--) bits.push((value >>> i) & 1);
|
|
2131
|
-
}
|
|
2132
|
-
push(MODE_BYTE, 4);
|
|
2133
|
-
push(bytes.length, ccBits);
|
|
2134
|
-
for (var i = 0; i < bytes.length; i++) push(bytes[i], 8);
|
|
2135
|
-
var capacity = numDataCodewords(ver) * 8;
|
|
2136
|
-
push(0, Math.min(4, capacity - bits.length));
|
|
2137
|
-
push(0, (8 - (bits.length % 8)) % 8);
|
|
2138
|
-
for (var pad = 0xec; bits.length < capacity; pad ^= 0xec ^ 0x11) push(pad, 8);
|
|
2139
|
-
var codewords = [];
|
|
2140
|
-
for (var i = 0; i < bits.length; i += 8) {
|
|
2141
|
-
var b = 0;
|
|
2142
|
-
for (var j = 0; j < 8; j++) b = (b << 1) | bits[i + j];
|
|
2143
|
-
codewords.push(b);
|
|
2144
|
-
}
|
|
2145
|
-
return codewords;
|
|
2146
|
-
}
|
|
2147
|
-
|
|
2148
|
-
function splitBlocks(data, ver) {
|
|
2149
|
-
var t = ECC_TABLE[ver - 1];
|
|
2150
|
-
var eccLen = t[0];
|
|
2151
|
-
var numBlocks = t[1];
|
|
2152
|
-
var rawCodewords = Math.floor(numRawDataModules(ver) / 8);
|
|
2153
|
-
var numShort = numBlocks - (rawCodewords % numBlocks);
|
|
2154
|
-
var shortBlockLen = Math.floor(rawCodewords / numBlocks);
|
|
2155
|
-
var divisor = rsDivisor(eccLen);
|
|
2156
|
-
var blocks = [];
|
|
2157
|
-
var k = 0;
|
|
2158
|
-
for (var i = 0; i < numBlocks; i++) {
|
|
2159
|
-
var dataLen = shortBlockLen - eccLen + (i < numShort ? 0 : 1);
|
|
2160
|
-
var dat = data.slice(k, k + dataLen);
|
|
2161
|
-
k += dataLen;
|
|
2162
|
-
blocks.push({ data: dat, ecc: rsRemainder(dat, divisor) });
|
|
2163
|
-
}
|
|
2164
|
-
return blocks;
|
|
2165
|
-
}
|
|
2166
|
-
|
|
2167
|
-
function interleave(blocks) {
|
|
2168
|
-
var out = [];
|
|
2169
|
-
var maxData = 0;
|
|
2170
|
-
var eccLen = blocks[0].ecc.length;
|
|
2171
|
-
for (var b = 0; b < blocks.length; b++) {
|
|
2172
|
-
if (blocks[b].data.length > maxData) maxData = blocks[b].data.length;
|
|
2173
|
-
}
|
|
2174
|
-
for (var i = 0; i < maxData; i++) {
|
|
2175
|
-
for (var j = 0; j < blocks.length; j++) {
|
|
2176
|
-
if (i < blocks[j].data.length) out.push(blocks[j].data[i]);
|
|
2177
|
-
}
|
|
2178
|
-
}
|
|
2179
|
-
for (var i = 0; i < eccLen; i++) {
|
|
2180
|
-
for (var j = 0; j < blocks.length; j++) out.push(blocks[j].ecc[i]);
|
|
2181
|
-
}
|
|
2182
|
-
return out;
|
|
2183
|
-
}
|
|
2184
|
-
|
|
2185
|
-
// \u2500\u2500 Matrix \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
2186
|
-
|
|
2187
|
-
function newMatrix(size) {
|
|
2188
|
-
var modules = [];
|
|
2189
|
-
var isFunction = [];
|
|
2190
|
-
for (var y = 0; y < size; y++) {
|
|
2191
|
-
modules.push(new Array(size).fill(false));
|
|
2192
|
-
isFunction.push(new Array(size).fill(false));
|
|
2193
|
-
}
|
|
2194
|
-
return { modules: modules, isFunction: isFunction, size: size };
|
|
2195
|
-
}
|
|
2196
|
-
|
|
2197
|
-
function setFunction(m, x, y, dark) {
|
|
2198
|
-
m.modules[y][x] = dark;
|
|
2199
|
-
m.isFunction[y][x] = true;
|
|
2200
|
-
}
|
|
2201
|
-
|
|
2202
|
-
function drawFinder(m, cx, cy) {
|
|
2203
|
-
for (var dy = -4; dy <= 4; dy++) {
|
|
2204
|
-
for (var dx = -4; dx <= 4; dx++) {
|
|
2205
|
-
var x = cx + dx;
|
|
2206
|
-
var y = cy + dy;
|
|
2207
|
-
if (x < 0 || x >= m.size || y < 0 || y >= m.size) continue;
|
|
2208
|
-
var dist = Math.max(Math.abs(dx), Math.abs(dy));
|
|
2209
|
-
setFunction(m, x, y, dist !== 2 && dist !== 4);
|
|
2210
|
-
}
|
|
2211
|
-
}
|
|
2212
|
-
}
|
|
2213
|
-
|
|
2214
|
-
function drawAlignment(m, cx, cy) {
|
|
2215
|
-
for (var dy = -2; dy <= 2; dy++) {
|
|
2216
|
-
for (var dx = -2; dx <= 2; dx++) {
|
|
2217
|
-
setFunction(m, cx + dx, cy + dy, Math.max(Math.abs(dx), Math.abs(dy)) !== 1);
|
|
2218
|
-
}
|
|
2219
|
-
}
|
|
2220
|
-
}
|
|
2221
|
-
|
|
2222
|
-
function drawFunctionPatterns(m, ver) {
|
|
2223
|
-
for (var i = 0; i < m.size; i++) {
|
|
2224
|
-
setFunction(m, 6, i, i % 2 === 0);
|
|
2225
|
-
setFunction(m, i, 6, i % 2 === 0);
|
|
2226
|
-
}
|
|
2227
|
-
drawFinder(m, 3, 3);
|
|
2228
|
-
drawFinder(m, m.size - 4, 3);
|
|
2229
|
-
drawFinder(m, 3, m.size - 4);
|
|
2230
|
-
var pos = alignmentPositions(ver);
|
|
2231
|
-
for (var i = 0; i < pos.length; i++) {
|
|
2232
|
-
for (var j = 0; j < pos.length; j++) {
|
|
2233
|
-
var corner = (i === 0 && j === 0) ||
|
|
2234
|
-
(i === 0 && j === pos.length - 1) ||
|
|
2235
|
-
(i === pos.length - 1 && j === 0);
|
|
2236
|
-
if (!corner) drawAlignment(m, pos[i], pos[j]);
|
|
2237
|
-
}
|
|
2238
|
-
}
|
|
2239
|
-
drawFormatBits(m, 0);
|
|
2240
|
-
drawVersionBits(m, ver);
|
|
2241
|
-
}
|
|
2242
|
-
|
|
2243
|
-
function drawFormatBits(m, mask) {
|
|
2244
|
-
var data = (FORMAT_BITS_M << 3) | mask;
|
|
2245
|
-
var rem = data;
|
|
2246
|
-
for (var i = 0; i < 10; i++) rem = (rem << 1) ^ ((rem >>> 9) * 0x537);
|
|
2247
|
-
var bits = ((data << 10) | rem) ^ 0x5412;
|
|
2248
|
-
for (var i = 0; i <= 5; i++) setFunction(m, 8, i, ((bits >>> i) & 1) !== 0);
|
|
2249
|
-
setFunction(m, 8, 7, ((bits >>> 6) & 1) !== 0);
|
|
2250
|
-
setFunction(m, 8, 8, ((bits >>> 7) & 1) !== 0);
|
|
2251
|
-
setFunction(m, 7, 8, ((bits >>> 8) & 1) !== 0);
|
|
2252
|
-
for (var i = 9; i < 15; i++) setFunction(m, 14 - i, 8, ((bits >>> i) & 1) !== 0);
|
|
2253
|
-
for (var i = 0; i < 8; i++) setFunction(m, m.size - 1 - i, 8, ((bits >>> i) & 1) !== 0);
|
|
2254
|
-
for (var i = 8; i < 15; i++) setFunction(m, 8, m.size - 15 + i, ((bits >>> i) & 1) !== 0);
|
|
2255
|
-
setFunction(m, 8, m.size - 8, true);
|
|
2256
|
-
}
|
|
2257
|
-
|
|
2258
|
-
function drawVersionBits(m, ver) {
|
|
2259
|
-
if (ver < 7) return;
|
|
2260
|
-
var rem = ver;
|
|
2261
|
-
for (var i = 0; i < 12; i++) rem = (rem << 1) ^ ((rem >>> 11) * 0x1f25);
|
|
2262
|
-
var bits = (ver << 12) | rem;
|
|
2263
|
-
for (var i = 0; i < 18; i++) {
|
|
2264
|
-
var dark = ((bits >>> i) & 1) !== 0;
|
|
2265
|
-
var a = m.size - 11 + (i % 3);
|
|
2266
|
-
var b = Math.floor(i / 3);
|
|
2267
|
-
setFunction(m, a, b, dark);
|
|
2268
|
-
setFunction(m, b, a, dark);
|
|
2269
|
-
}
|
|
2270
|
-
}
|
|
2271
|
-
|
|
2272
|
-
function drawCodewords(m, codewords) {
|
|
2273
|
-
var bitIndex = 0;
|
|
2274
|
-
var total = codewords.length * 8;
|
|
2275
|
-
for (var right = m.size - 1; right >= 1; right -= 2) {
|
|
2276
|
-
if (right === 6) right = 5;
|
|
2277
|
-
for (var vert = 0; vert < m.size; vert++) {
|
|
2278
|
-
for (var j = 0; j < 2; j++) {
|
|
2279
|
-
var x = right - j;
|
|
2280
|
-
var upward = ((right + 1) & 2) === 0;
|
|
2281
|
-
var y = upward ? m.size - 1 - vert : vert;
|
|
2282
|
-
if (!m.isFunction[y][x] && bitIndex < total) {
|
|
2283
|
-
m.modules[y][x] = ((codewords[bitIndex >>> 3] >>> (7 - (bitIndex & 7))) & 1) !== 0;
|
|
2284
|
-
bitIndex++;
|
|
2285
|
-
}
|
|
2286
|
-
}
|
|
2287
|
-
}
|
|
2288
|
-
}
|
|
2289
|
-
}
|
|
2290
|
-
|
|
2291
|
-
function maskAt(mask, x, y) {
|
|
2292
|
-
switch (mask) {
|
|
2293
|
-
case 0: return (x + y) % 2 === 0;
|
|
2294
|
-
case 1: return y % 2 === 0;
|
|
2295
|
-
case 2: return x % 3 === 0;
|
|
2296
|
-
case 3: return (x + y) % 3 === 0;
|
|
2297
|
-
case 4: return (Math.floor(x / 3) + Math.floor(y / 2)) % 2 === 0;
|
|
2298
|
-
case 5: return (x * y) % 2 + (x * y) % 3 === 0;
|
|
2299
|
-
case 6: return ((x * y) % 2 + (x * y) % 3) % 2 === 0;
|
|
2300
|
-
default: return ((x + y) % 2 + (x * y) % 3) % 2 === 0;
|
|
2301
|
-
}
|
|
2302
|
-
}
|
|
2303
|
-
|
|
2304
|
-
function applyMask(m, mask) {
|
|
2305
|
-
for (var y = 0; y < m.size; y++) {
|
|
2306
|
-
for (var x = 0; x < m.size; x++) {
|
|
2307
|
-
if (!m.isFunction[y][x] && maskAt(mask, x, y)) m.modules[y][x] = !m.modules[y][x];
|
|
2308
|
-
}
|
|
2309
|
-
}
|
|
2310
|
-
}
|
|
2311
|
-
|
|
2312
|
-
function penalty(m) {
|
|
2313
|
-
var score = 0;
|
|
2314
|
-
var size = m.size;
|
|
2315
|
-
var x, y, i;
|
|
2316
|
-
// Rule 1: runs of five or more same-colour modules.
|
|
2317
|
-
for (y = 0; y < size; y++) {
|
|
2318
|
-
var runColor = m.modules[y][0];
|
|
2319
|
-
var runLen = 1;
|
|
2320
|
-
for (x = 1; x < size; x++) {
|
|
2321
|
-
if (m.modules[y][x] === runColor) {
|
|
2322
|
-
runLen++;
|
|
2323
|
-
} else {
|
|
2324
|
-
if (runLen >= 5) score += 3 + (runLen - 5);
|
|
2325
|
-
runColor = m.modules[y][x];
|
|
2326
|
-
runLen = 1;
|
|
2327
|
-
}
|
|
2328
|
-
}
|
|
2329
|
-
if (runLen >= 5) score += 3 + (runLen - 5);
|
|
2330
|
-
}
|
|
2331
|
-
for (x = 0; x < size; x++) {
|
|
2332
|
-
var colColor = m.modules[0][x];
|
|
2333
|
-
var colLen = 1;
|
|
2334
|
-
for (y = 1; y < size; y++) {
|
|
2335
|
-
if (m.modules[y][x] === colColor) {
|
|
2336
|
-
colLen++;
|
|
2337
|
-
} else {
|
|
2338
|
-
if (colLen >= 5) score += 3 + (colLen - 5);
|
|
2339
|
-
colColor = m.modules[y][x];
|
|
2340
|
-
colLen = 1;
|
|
2341
|
-
}
|
|
2342
|
-
}
|
|
2343
|
-
if (colLen >= 5) score += 3 + (colLen - 5);
|
|
2344
|
-
}
|
|
2345
|
-
// Rule 2: 2x2 blocks of one colour.
|
|
2346
|
-
for (y = 0; y < size - 1; y++) {
|
|
2347
|
-
for (x = 0; x < size - 1; x++) {
|
|
2348
|
-
var c = m.modules[y][x];
|
|
2349
|
-
if (c === m.modules[y][x + 1] && c === m.modules[y + 1][x] && c === m.modules[y + 1][x + 1]) score += 3;
|
|
2350
|
-
}
|
|
2351
|
-
}
|
|
2352
|
-
// Rule 3: finder-like 1:1:3:1:1 patterns with four light modules beside.
|
|
2353
|
-
var pattern = [true, false, true, true, true, false, true];
|
|
2354
|
-
var hasPattern = function (get, at) {
|
|
2355
|
-
for (var k = 0; k < 7; k++) {
|
|
2356
|
-
if (get(at + k) !== pattern[k]) return false;
|
|
2357
|
-
}
|
|
2358
|
-
return true;
|
|
2359
|
-
};
|
|
2360
|
-
var lightRun = function (get, at, count) {
|
|
2361
|
-
for (var k = 1; k <= count; k++) {
|
|
2362
|
-
if (at - k < 0) return false;
|
|
2363
|
-
if (get(at - k) !== false) return false;
|
|
2364
|
-
}
|
|
2365
|
-
return true;
|
|
2366
|
-
};
|
|
2367
|
-
for (y = 0; y < size; y++) {
|
|
2368
|
-
for (x = 0; x <= size - 7; x++) {
|
|
2369
|
-
if (hasPattern(function (at) { return m.modules[y][at]; }, x)) {
|
|
2370
|
-
if (lightRun(function (at) { return m.modules[y][at]; }, x, 4)) score += 40;
|
|
2371
|
-
if (x + 11 <= size && lightRun(function (at) { return m.modules[y][at]; }, x + 7, 4)) score += 40;
|
|
2372
|
-
}
|
|
2373
|
-
}
|
|
2374
|
-
}
|
|
2375
|
-
for (x = 0; x < size; x++) {
|
|
2376
|
-
for (y = 0; y <= size - 7; y++) {
|
|
2377
|
-
if (hasPattern(function (at) { return m.modules[at][x]; }, y)) {
|
|
2378
|
-
if (lightRun(function (at) { return m.modules[at][x]; }, y, 4)) score += 40;
|
|
2379
|
-
if (y + 11 <= size && lightRun(function (at) { return m.modules[at][x]; }, y + 7, 4)) score += 40;
|
|
2380
|
-
}
|
|
2381
|
-
}
|
|
2382
|
-
}
|
|
2383
|
-
// Rule 4: deviation from a 50/50 dark ratio.
|
|
2384
|
-
var dark = 0;
|
|
2385
|
-
for (y = 0; y < size; y++) {
|
|
2386
|
-
for (x = 0; x < size; x++) if (m.modules[y][x]) dark++;
|
|
2387
|
-
}
|
|
2388
|
-
var ratio = Math.ceil(Math.abs(dark * 20 - size * size * 10) / (size * size)) - 1;
|
|
2389
|
-
score += ratio * 10;
|
|
2390
|
-
return score;
|
|
2391
|
-
}
|
|
2392
|
-
|
|
2393
|
-
/**
|
|
2394
|
-
* Encode text as a QR module matrix: { size, modules } where modules[y][x]
|
|
2395
|
-
* is true for a dark module.
|
|
2396
|
-
*/
|
|
2397
|
-
function qrMatrix(text) {
|
|
2398
|
-
var bytes = utf8Bytes(text);
|
|
2399
|
-
var ver = 0;
|
|
2400
|
-
for (var v = 1; v <= MAX_VERSION; v++) {
|
|
2401
|
-
var ccBits = v <= 9 ? 8 : 16;
|
|
2402
|
-
if (4 + ccBits + bytes.length * 8 <= numDataCodewords(v) * 8) { ver = v; break; }
|
|
2403
|
-
}
|
|
2404
|
-
if (!ver) throw new Error('QR payload too long');
|
|
2405
|
-
var codewords = interleave(splitBlocks(buildCodewords(text, ver), ver));
|
|
2406
|
-
var base = newMatrix(ver * 4 + 17);
|
|
2407
|
-
drawFunctionPatterns(base, ver);
|
|
2408
|
-
drawCodewords(base, codewords);
|
|
2409
|
-
var best = null;
|
|
2410
|
-
for (var mask = 0; mask < 8; mask++) {
|
|
2411
|
-
var candidate = {
|
|
2412
|
-
modules: base.modules.map(function (row) { return row.slice(); }),
|
|
2413
|
-
isFunction: base.isFunction,
|
|
2414
|
-
size: base.size
|
|
2415
|
-
};
|
|
2416
|
-
applyMask(candidate, mask);
|
|
2417
|
-
drawFormatBits(candidate, mask);
|
|
2418
|
-
var score = penalty(candidate);
|
|
2419
|
-
if (!best || score < best.score) best = { score: score, matrix: candidate };
|
|
2420
|
-
}
|
|
2421
|
-
return { size: best.matrix.size, modules: best.matrix.modules };
|
|
2422
|
-
}
|
|
2423
|
-
|
|
2424
|
-
/** Render text as an inline SVG QR code (no external assets). */
|
|
2425
|
-
function qrSvg(text) {
|
|
2426
|
-
var qr = qrMatrix(text);
|
|
2427
|
-
var margin = 4;
|
|
2428
|
-
var size = qr.size;
|
|
2429
|
-
var parts = [];
|
|
2430
|
-
for (var y = 0; y < size; y++) {
|
|
2431
|
-
var x = 0;
|
|
2432
|
-
while (x < size) {
|
|
2433
|
-
if (qr.modules[y][x]) {
|
|
2434
|
-
var run = 1;
|
|
2435
|
-
while (x + run < size && qr.modules[y][x + run]) run++;
|
|
2436
|
-
parts.push('M' + x + ' ' + y + 'h' + run + 'v1h-' + run + 'z');
|
|
2437
|
-
x += run;
|
|
2438
|
-
} else {
|
|
2439
|
-
x++;
|
|
2440
|
-
}
|
|
2441
|
-
}
|
|
2442
|
-
}
|
|
2443
|
-
var dim = size + margin * 2;
|
|
2444
|
-
return '<svg xmlns="http://www.w3.org/2000/svg" viewBox="' + (-margin) + ' ' + (-margin) + ' ' + dim + ' ' + dim +
|
|
2445
|
-
'" shape-rendering="crispEdges" role="img" aria-label="Subscription QR code" class="qr-svg">' +
|
|
2446
|
-
'<rect x="' + (-margin) + '" y="' + (-margin) + '" width="' + dim + '" height="' + dim + '" fill="#ffffff"/>' +
|
|
2447
|
-
'<path d="' + parts.join('') + '" fill="#000000"/></svg>';
|
|
2448
|
-
}
|
|
2449
|
-
|
|
2450
|
-
// \u2500\u2500 Subscription deep links \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
2451
|
-
|
|
2452
|
-
/** The feed's own directory URL, as served. */
|
|
2453
|
-
function feedUrl() {
|
|
2454
|
-
return new URL('.', window.location.href).href;
|
|
2455
|
-
}
|
|
2456
|
-
|
|
2457
|
-
/**
|
|
2458
|
-
* Subscription deep link for the whole feed, or for one notebook
|
|
2459
|
-
* (the chunk id's slug, e.g. notebook.cat1 \u2192 cat1).
|
|
2460
|
-
*/
|
|
2461
|
-
function subscribeUrl(notebookId) {
|
|
2462
|
-
var url = APP_ORIGIN + '/subscribe?source=' + encodeURIComponent(feedUrl());
|
|
2463
|
-
if (notebookId) {
|
|
2464
|
-
url += '¬ebook=' + encodeURIComponent(String(notebookId).replace(/^notebook\\./, ''));
|
|
2465
|
-
}
|
|
2466
|
-
return url;
|
|
2467
|
-
}
|
|
2468
|
-
|
|
2469
|
-
function each(root, selector, fn) {
|
|
2470
|
-
var nodes = root.querySelectorAll(selector);
|
|
2471
|
-
for (var i = 0; i < nodes.length; i++) fn(nodes[i]);
|
|
2472
|
-
}
|
|
2473
|
-
|
|
2474
|
-
function render(root) {
|
|
2475
|
-
var feed = subscribeUrl(null);
|
|
2476
|
-
each(root, '[data-subscribe-feed]', function (el) { el.setAttribute('href', feed); });
|
|
2477
|
-
each(root, '[data-subscribe-notebook]', function (el) {
|
|
2478
|
-
el.setAttribute('href', subscribeUrl(el.getAttribute('data-subscribe-notebook')));
|
|
2479
|
-
});
|
|
2480
|
-
each(root, '[data-qr-feed]', function (el) { el.innerHTML = qrSvg(feed); });
|
|
2481
|
-
each(root, '[data-qr-notebook]', function (el) {
|
|
2482
|
-
el.innerHTML = qrSvg(subscribeUrl(el.getAttribute('data-qr-notebook')));
|
|
2483
|
-
});
|
|
2484
|
-
}
|
|
2485
|
-
|
|
2486
|
-
var api = { feedUrl: feedUrl, subscribeUrl: subscribeUrl, qrSvg: qrSvg, qrMatrix: qrMatrix, render: render };
|
|
2487
|
-
window.wodFeedLanding = api;
|
|
2488
|
-
|
|
2489
|
-
if (typeof document !== 'undefined') {
|
|
2490
|
-
if (document.readyState === 'loading') {
|
|
2491
|
-
document.addEventListener('DOMContentLoaded', function () { render(document); });
|
|
2492
|
-
} else {
|
|
2493
|
-
render(document);
|
|
2494
|
-
}
|
|
2495
|
-
}
|
|
2496
|
-
})();`;
|
|
2497
|
-
|
|
2498
|
-
// src/feed/landing.ts
|
|
2499
|
-
function escapeHtml(s) {
|
|
2500
|
-
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
2501
|
-
}
|
|
2502
|
-
function isoDate(ms) {
|
|
2503
|
-
if (ms === void 0 || !Number.isFinite(ms)) return "";
|
|
2504
|
-
const d = new Date(ms);
|
|
2505
|
-
return Number.isNaN(d.getTime()) ? "" : d.toISOString().slice(0, 10);
|
|
2506
|
-
}
|
|
2507
|
-
function chunkRowHtml(c) {
|
|
2508
|
-
const kind = c.kind ?? "notes";
|
|
2509
|
-
return `<tr><td>${escapeHtml(c.id)}</td><td>${kind}</td><td>${c.count}</td><td>${(c.bytes / 1024).toFixed(1)} KB</td><td><code>${c.sha256.slice(0, 8)}</code></td></tr>`;
|
|
2510
|
-
}
|
|
2511
|
-
function noteHtml(note) {
|
|
2512
|
-
const date = isoDate(note.date);
|
|
2513
|
-
const dataTag = note.publicSessions && note.publicSessions > 0 ? ` \xB7 <strong>+${note.publicSessions} session${note.publicSessions === 1 ? "" : "s"}</strong>` : "";
|
|
2514
|
-
const meta = [date, `<code>${escapeHtml(note.path)}</code>`].filter(Boolean).join(" \xB7 ");
|
|
2515
|
-
const source = note.content ? `<details><summary>source</summary><pre>${escapeHtml(note.content)}</pre></details>` : "";
|
|
2516
|
-
const record = note.recordPath ? ` \xB7 <a href="${escapeHtml(note.recordPath)}">record</a>` : "";
|
|
2517
|
-
return ` <li><span class="title">${escapeHtml(note.title)}</span> <span class="meta">${meta}${record}${dataTag}</span>${source}</li>`;
|
|
2518
|
-
}
|
|
2519
|
-
function notebookHtml(notebook) {
|
|
2520
|
-
const notes = notebook.notes.map(noteHtml).join("\n");
|
|
2521
|
-
return ` <section class="notebook">
|
|
2522
|
-
<h3>${escapeHtml(notebook.label)} <small>${escapeHtml(notebook.id)} \xB7 ${notebook.notes.length} note${notebook.notes.length === 1 ? "" : "s"}</small></h3>
|
|
2523
|
-
<p class="subscribe-row"><a class="subscribe" data-subscribe-notebook="${escapeHtml(notebook.id)}">Subscribe to Notebook</a> <details class="qr"><summary>QR</summary><div class="qr-body" data-qr-notebook="${escapeHtml(notebook.id)}"></div></details></p>
|
|
2524
|
-
<ul>
|
|
2525
|
-
${notes}
|
|
2526
|
-
</ul>
|
|
2527
|
-
</section>`;
|
|
2528
|
-
}
|
|
2529
|
-
function renderFeedLandingHtml(data) {
|
|
2530
|
-
const { manifest, totalMs, passMs, fileCount, notebooks, appOrigin = APP_ORIGIN } = data;
|
|
2531
|
-
const totalBytes = manifest.chunks.reduce((s, c) => s + c.bytes, 0);
|
|
2532
|
-
const totalNotes = notebooks.reduce((s, n) => s + n.notes.length, 0);
|
|
2533
|
-
const dirtyBadge = manifest.dirty ? ' <strong style="color:#b45309">(dirty working tree \u2014 not reproducible from <code>' + escapeHtml(manifest.commit ?? "") + "</code>)</strong>" : "";
|
|
2534
|
-
const title = manifest.name ? `${manifest.name} \u2014 feed` : "Feed";
|
|
2535
|
-
const description = manifest.description ? `<p class="desc">${escapeHtml(manifest.description)}</p>` : "";
|
|
2536
|
-
const repoLink = manifest.repositoryUrl ? `<p class="meta"><a href="${escapeHtml(manifest.repositoryUrl)}">${escapeHtml(manifest.repositoryUrl)}</a></p>` : "";
|
|
2537
|
-
const contents = notebooks.length ? notebooks.map(notebookHtml).join("\n") : ' <p class="meta">This feed publishes no notebooks yet.</p>';
|
|
2538
|
-
return `<!doctype html>
|
|
2539
|
-
<html lang="en">
|
|
2540
|
-
<head>
|
|
2541
|
-
<meta charset="utf-8" />
|
|
2542
|
-
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
2543
|
-
<title>${escapeHtml(title)}</title>
|
|
2544
|
-
<style>
|
|
2545
|
-
body { font-family: system-ui, sans-serif; max-width: 960px; margin: 2rem auto; padding: 0 1rem; color: #1f2937; }
|
|
2546
|
-
h1 { font-size: 1.4rem; } h2 { font-size: 1.1rem; margin-top: 2rem; }
|
|
2547
|
-
h3 { font-size: 1rem; margin: 1.25rem 0 .25rem; }
|
|
2548
|
-
table { border-collapse: collapse; width: 100%; font-size: 0.9rem; }
|
|
2549
|
-
th, td { text-align: left; padding: 0.3rem 0.6rem; border-bottom: 1px solid #e5e7eb; }
|
|
2550
|
-
code { font-size: 0.85em; }
|
|
2551
|
-
dl { display: grid; grid-template-columns: max-content 1fr; gap: 0.2rem 1rem; font-size: 0.95rem; }
|
|
2552
|
-
dt { font-weight: 600; }
|
|
2553
|
-
ul { list-style: none; padding-left: 0; margin: .25rem 0 0; }
|
|
2554
|
-
li { padding: .35rem 0; border-bottom: 1px solid #e5e7eb; }
|
|
2555
|
-
li .title { font-weight: 600; }
|
|
2556
|
-
.meta { color: #6b7280; font-size: 0.85rem; }
|
|
2557
|
-
.desc { font-size: 1rem; }
|
|
2558
|
-
pre { overflow-x: auto; background: #f3f4f6; padding: 0.6rem; border-radius: 0.25rem; font-size: 0.8rem; }
|
|
2559
|
-
summary { cursor: pointer; color: #6b7280; font-size: 0.85rem; }
|
|
2560
|
-
small { font-weight: 400; color: #6b7280; }
|
|
2561
|
-
.subscribe { display: inline-block; padding: .4rem .8rem; border: 1px solid #1f2937; border-radius: .25rem; color: #1f2937; text-decoration: none; font-size: .9rem; }
|
|
2562
|
-
.subscribe.primary { background: #1f2937; color: #fff; }
|
|
2563
|
-
.subscribe-row { margin: .4rem 0 .2rem; }
|
|
2564
|
-
.qr { display: inline-block; vertical-align: middle; margin-left: .5rem; }
|
|
2565
|
-
.qr-body { padding: .4rem 0; }
|
|
2566
|
-
.qr-svg { width: 132px; height: 132px; display: block; }
|
|
2567
|
-
</style>
|
|
2568
|
-
</head>
|
|
2569
|
-
<body>
|
|
2570
|
-
<h1>${escapeHtml(manifest.name ?? "Feed")}</h1>
|
|
2571
|
-
${description}
|
|
2572
|
-
${repoLink}
|
|
2573
|
-
<p class="meta"><a href="manifest.json">manifest.json</a> \u2014 the artifact subscribers import.</p>
|
|
2574
|
-
<section class="subscribe">
|
|
2575
|
-
<a class="subscribe primary" data-subscribe-feed>Subscribe to Whole Feed</a>
|
|
2576
|
-
<details class="qr"><summary>QR</summary><div class="qr-body" data-qr-feed></div></details>
|
|
2577
|
-
<p class="meta">Opens Wod.Wiki and subscribes to every notebook this feed publishes. <noscript>JavaScript is off \u2014 subscribe from Wod.Wiki with this feed's URL.</noscript></p>
|
|
2578
|
-
</section>
|
|
2579
|
-
<h2>Contents</h2>
|
|
2580
|
-
<p class="meta">${notebooks.length} notebook${notebooks.length === 1 ? "" : "s"} \xB7 ${totalNotes} note${totalNotes === 1 ? "" : "s"}</p>
|
|
2581
|
-
${contents}
|
|
2582
|
-
<h2>Version</h2>
|
|
2583
|
-
<dl>
|
|
2584
|
-
<dt>version</dt><dd>${manifest.version} <code>${escapeHtml(manifest.versionLabel ?? "")}</code>${dirtyBadge}</dd>
|
|
2585
|
-
<dt>commit</dt><dd><code>${escapeHtml(manifest.commit ?? "unknown")}</code></dd>
|
|
2586
|
-
<dt>built at</dt><dd>${escapeHtml(manifest.builtAt)}</dd>
|
|
2587
|
-
<dt>schema</dt><dd>v${manifest.schema}</dd>
|
|
2588
|
-
</dl>
|
|
2589
|
-
<h2>Build report</h2>
|
|
2590
|
-
<dl>
|
|
2591
|
-
<dt>total</dt><dd>${totalMs} ms</dd>
|
|
2592
|
-
<dt>corpus scan + partition</dt><dd>${passMs.scan} ms (${fileCount} files)</dd>
|
|
2593
|
-
<dt>block-index derivation</dt><dd>${passMs.blockIndex} ms</dd>
|
|
2594
|
-
<dt>block syntax gate</dt><dd>${passMs.parseGate} ms</dd>
|
|
2595
|
-
<dt>block-efforts derivation</dt><dd>${passMs.blockEfforts} ms</dd>
|
|
2596
|
-
<dt>chunk writes</dt><dd>${passMs.write} ms</dd>
|
|
2597
|
-
</dl>
|
|
2598
|
-
<h2>Chunks (${manifest.chunks.length}, ${(totalBytes / 1024).toFixed(0)} KB total)</h2>
|
|
2599
|
-
<table>
|
|
2600
|
-
<thead><tr><th>id</th><th>kind</th><th>rows</th><th>size</th><th>sha256</th></tr></thead>
|
|
2601
|
-
<tbody>
|
|
2602
|
-
${manifest.chunks.map(chunkRowHtml).join("\n")}
|
|
2603
|
-
</tbody>
|
|
2604
|
-
</table>
|
|
2605
|
-
<script id="${QR_SCRIPT_ID}">
|
|
2606
|
-
${qrInlineScript(appOrigin)}
|
|
2607
|
-
</script>
|
|
2608
|
-
</body>
|
|
2609
|
-
</html>
|
|
2610
|
-
`;
|
|
2611
|
-
}
|
|
2612
|
-
|
|
2613
|
-
// src/feed/tree.ts
|
|
2614
|
-
var FeedTreeError = class extends Error {
|
|
2615
|
-
constructor(code, message) {
|
|
2616
|
-
super(message);
|
|
2617
|
-
this.code = code;
|
|
2618
|
-
this.name = "FeedTreeError";
|
|
2619
|
-
}
|
|
2620
|
-
code;
|
|
2621
|
-
};
|
|
2622
|
-
var encoder = new TextEncoder();
|
|
2623
|
-
var decoder = new TextDecoder();
|
|
2624
|
-
function encodeUtf8(text) {
|
|
2625
|
-
return encoder.encode(text);
|
|
2626
|
-
}
|
|
2627
|
-
function decodeUtf8(bytes) {
|
|
2628
|
-
return decoder.decode(bytes);
|
|
2629
|
-
}
|
|
2630
|
-
function normalizeFeedTreePath(rawPath) {
|
|
2631
|
-
if (!rawPath || rawPath.includes("\0") || rawPath.includes("\\")) {
|
|
2632
|
-
throw new FeedTreeError("layout", `Invalid feed path '${rawPath}'`);
|
|
2633
|
-
}
|
|
2634
|
-
const trimmed = rawPath.replace(/^\/+|\/+$/g, "");
|
|
2635
|
-
if (!trimmed) {
|
|
2636
|
-
throw new FeedTreeError("layout", "Feed path must not be empty");
|
|
2637
|
-
}
|
|
2638
|
-
const parts = trimmed.split("/");
|
|
2639
|
-
for (const part of parts) {
|
|
2640
|
-
if (!part || part === "." || part === "..") {
|
|
2641
|
-
throw new FeedTreeError("layout", `Disallowed path segment in '${rawPath}'`);
|
|
2642
|
-
}
|
|
2643
|
-
}
|
|
2644
|
-
return parts.join("/");
|
|
2645
|
-
}
|
|
2646
|
-
async function sha256HexAsync(input) {
|
|
2647
|
-
const data = typeof input === "string" ? encoder.encode(input) : input;
|
|
2648
|
-
const copy = new Uint8Array(data.byteLength);
|
|
2649
|
-
copy.set(data);
|
|
2650
|
-
const digest = await crypto.subtle.digest("SHA-256", copy.buffer);
|
|
2651
|
-
return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("");
|
|
2652
|
-
}
|
|
2653
|
-
var MemoryFeedTree = class {
|
|
2654
|
-
store = /* @__PURE__ */ new Map();
|
|
2655
|
-
constructor(initial) {
|
|
2656
|
-
if (initial) {
|
|
2657
|
-
for (const [k, v] of Object.entries(initial)) {
|
|
2658
|
-
const p = normalizeFeedTreePath(k);
|
|
2659
|
-
this.store.set(p, typeof v === "string" ? encodeUtf8(v) : new Uint8Array(v));
|
|
2660
|
-
}
|
|
2661
|
-
}
|
|
2662
|
-
}
|
|
2663
|
-
async read(path) {
|
|
2664
|
-
const p = normalizeFeedTreePath(path);
|
|
2665
|
-
const bytes = this.store.get(p);
|
|
2666
|
-
if (!bytes) throw new FeedTreeError("not-found", `Missing feed entry: ${p}`);
|
|
2667
|
-
return new Uint8Array(bytes);
|
|
2668
|
-
}
|
|
2669
|
-
async readText(path) {
|
|
2670
|
-
return decodeUtf8(await this.read(path));
|
|
2671
|
-
}
|
|
2672
|
-
async stat(path) {
|
|
2673
|
-
const p = normalizeFeedTreePath(path);
|
|
2674
|
-
const bytes = this.store.get(p);
|
|
2675
|
-
if (!bytes) return void 0;
|
|
2676
|
-
return {
|
|
2677
|
-
bytes: bytes.byteLength,
|
|
2678
|
-
sha256: await sha256HexAsync(bytes)
|
|
2679
|
-
};
|
|
2680
|
-
}
|
|
2681
|
-
async write(path, bytes) {
|
|
2682
|
-
const p = normalizeFeedTreePath(path);
|
|
2683
|
-
const copy = new Uint8Array(bytes.byteLength);
|
|
2684
|
-
copy.set(bytes);
|
|
2685
|
-
this.store.set(p, copy);
|
|
2686
|
-
}
|
|
2687
|
-
async writeText(path, text) {
|
|
2688
|
-
await this.write(path, encodeUtf8(text));
|
|
2689
|
-
}
|
|
2690
|
-
async delete(path) {
|
|
2691
|
-
const p = normalizeFeedTreePath(path);
|
|
2692
|
-
this.store.delete(p);
|
|
2693
|
-
}
|
|
2694
|
-
async list(prefix = "") {
|
|
2695
|
-
const clean = prefix ? normalizeFeedTreePath(prefix) + "/" : "";
|
|
2696
|
-
return [...this.store.keys()].filter((k) => !clean || k.startsWith(clean) || k === clean.slice(0, -1)).sort();
|
|
2697
|
-
}
|
|
2698
|
-
entries() {
|
|
2699
|
-
return [...this.store.entries()].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
|
|
2700
|
-
}
|
|
2701
|
-
};
|
|
2702
|
-
var HttpFeedTree = class {
|
|
2703
|
-
baseUrl;
|
|
2704
|
-
fetchImpl;
|
|
2705
|
-
constructor(baseUrl, fetchImpl) {
|
|
2706
|
-
this.baseUrl = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
|
|
2707
|
-
this.fetchImpl = fetchImpl ?? ((input, init) => globalThis.fetch(input, init));
|
|
2708
|
-
}
|
|
2709
|
-
async read(path) {
|
|
2710
|
-
const clean = normalizeFeedTreePath(path);
|
|
2711
|
-
const isMutableIndex = clean === "manifest.json" || clean.endsWith("/manifest.json");
|
|
2712
|
-
const doFetch = this.fetchImpl;
|
|
2713
|
-
const res = await doFetch(`${this.baseUrl}${clean}`, {
|
|
2714
|
-
cache: isMutableIndex ? "no-cache" : "default"
|
|
2715
|
-
});
|
|
2716
|
-
if (res.status === 404) {
|
|
2717
|
-
throw new FeedTreeError("not-found", `HTTP 404 for ${this.baseUrl}${clean}`);
|
|
2718
|
-
}
|
|
2719
|
-
if (!res.ok) {
|
|
2720
|
-
throw new FeedTreeError("permission", `HTTP ${res.status} fetching ${this.baseUrl}${clean}`);
|
|
2721
|
-
}
|
|
2722
|
-
return new Uint8Array(await res.arrayBuffer());
|
|
2723
|
-
}
|
|
2724
|
-
async readJson(path) {
|
|
2725
|
-
const text = decodeUtf8(await this.read(path));
|
|
2726
|
-
return JSON.parse(text);
|
|
2727
|
-
}
|
|
2728
|
-
async stat(path) {
|
|
2729
|
-
try {
|
|
2730
|
-
const bytes = await this.read(path);
|
|
2731
|
-
return { bytes: bytes.byteLength, sha256: await sha256HexAsync(bytes) };
|
|
2732
|
-
} catch (err) {
|
|
2733
|
-
if (err instanceof FeedTreeError && err.code === "not-found") return void 0;
|
|
2734
|
-
throw err;
|
|
2735
|
-
}
|
|
2736
|
-
}
|
|
2737
|
-
};
|
|
2738
|
-
var DirectoryHandleFeedTree = class {
|
|
2739
|
-
constructor(root) {
|
|
2740
|
-
this.root = root;
|
|
2741
|
-
}
|
|
2742
|
-
root;
|
|
2743
|
-
async resolveDir(segments, create) {
|
|
2744
|
-
let dir = this.root;
|
|
2745
|
-
for (const seg of segments) {
|
|
2746
|
-
dir = await dir.getDirectoryHandle(seg, { create });
|
|
2747
|
-
}
|
|
2748
|
-
return dir;
|
|
2749
|
-
}
|
|
2750
|
-
async read(path) {
|
|
2751
|
-
const clean = normalizeFeedTreePath(path);
|
|
2752
|
-
const parts = clean.split("/");
|
|
2753
|
-
const fileName = parts.pop();
|
|
2754
|
-
try {
|
|
2755
|
-
const dir = await this.resolveDir(parts, false);
|
|
2756
|
-
const handle = await dir.getFileHandle(fileName, { create: false });
|
|
2757
|
-
const file = await handle.getFile();
|
|
2758
|
-
return new Uint8Array(await file.arrayBuffer());
|
|
2759
|
-
} catch {
|
|
2760
|
-
throw new FeedTreeError("not-found", `Missing file '${clean}' in directory handle`);
|
|
2761
|
-
}
|
|
2762
|
-
}
|
|
2763
|
-
async stat(path) {
|
|
2764
|
-
try {
|
|
2765
|
-
const bytes = await this.read(path);
|
|
2766
|
-
return { bytes: bytes.byteLength, sha256: await sha256HexAsync(bytes) };
|
|
2767
|
-
} catch (err) {
|
|
2768
|
-
if (err instanceof FeedTreeError && err.code === "not-found") return void 0;
|
|
2769
|
-
throw err;
|
|
2770
|
-
}
|
|
2771
|
-
}
|
|
2772
|
-
async write(path, bytes) {
|
|
2773
|
-
const clean = normalizeFeedTreePath(path);
|
|
2774
|
-
const parts = clean.split("/");
|
|
2775
|
-
const fileName = parts.pop();
|
|
2776
|
-
try {
|
|
2777
|
-
const dir = await this.resolveDir(parts, true);
|
|
2778
|
-
const handle = await dir.getFileHandle(fileName, { create: true });
|
|
2779
|
-
const writable = await handle.createWritable();
|
|
2780
|
-
await writable.write(bytes);
|
|
2781
|
-
await writable.close();
|
|
2782
|
-
} catch (err) {
|
|
2783
|
-
throw new FeedTreeError(
|
|
2784
|
-
"permission",
|
|
2785
|
-
`Could not write '${clean}': ${err instanceof Error ? err.message : String(err)}`
|
|
2786
|
-
);
|
|
2787
|
-
}
|
|
2788
|
-
}
|
|
2789
|
-
async delete(path) {
|
|
2790
|
-
const clean = normalizeFeedTreePath(path);
|
|
2791
|
-
const parts = clean.split("/");
|
|
2792
|
-
const fileName = parts.pop();
|
|
2793
|
-
try {
|
|
2794
|
-
const dir = await this.resolveDir(parts, false);
|
|
2795
|
-
await dir.removeEntry(fileName);
|
|
2796
|
-
} catch {
|
|
2797
|
-
}
|
|
2798
|
-
}
|
|
2799
|
-
};
|
|
2800
|
-
var PUBLISHED_FEED_META_KEY = "publish:local-feed";
|
|
2801
|
-
function slugStem(raw, fallback) {
|
|
2802
|
-
const clean = raw.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
|
|
2803
|
-
return clean || fallback;
|
|
2804
|
-
}
|
|
2805
|
-
function repoWorkflowYaml() {
|
|
2806
|
-
return `name: Publish feed
|
|
2807
|
-
|
|
2808
|
-
on:
|
|
2809
|
-
push:
|
|
2810
|
-
branches: [main]
|
|
2811
|
-
workflow_dispatch:
|
|
2812
|
-
|
|
2813
|
-
permissions:
|
|
2814
|
-
contents: read
|
|
2815
|
-
pages: write
|
|
2816
|
-
id-token: write
|
|
2817
|
-
|
|
2818
|
-
concurrency:
|
|
2819
|
-
group: pages
|
|
2820
|
-
cancel-in-progress: true
|
|
2821
|
-
|
|
2822
|
-
jobs:
|
|
2823
|
-
publish:
|
|
2824
|
-
runs-on: ubuntu-latest
|
|
2825
|
-
environment:
|
|
2826
|
-
name: github-pages
|
|
2827
|
-
url: \${{ steps.deployment.outputs.page_url }}
|
|
2828
|
-
steps:
|
|
2829
|
-
- uses: actions/checkout@v4
|
|
2830
|
-
with:
|
|
2831
|
-
fetch-depth: 0
|
|
2832
|
-
- uses: oven-sh/setup-bun@v2
|
|
2833
|
-
with:
|
|
2834
|
-
bun-version: 1.4.x
|
|
2835
|
-
- name: Install dependencies
|
|
2836
|
-
run: bun install
|
|
2837
|
-
- name: Build seed
|
|
2838
|
-
run: bunx wod build . --output dist
|
|
2839
|
-
- uses: actions/configure-pages@v5
|
|
2840
|
-
- name: Upload dist
|
|
2841
|
-
uses: actions/upload-pages-artifact@v3
|
|
2842
|
-
with:
|
|
2843
|
-
path: dist
|
|
2844
|
-
- id: deployment
|
|
2845
|
-
uses: actions/deploy-pages@v4
|
|
2846
|
-
`;
|
|
2847
|
-
}
|
|
2848
|
-
function repoPackageJson(name, description, repositoryUrl) {
|
|
2849
|
-
const pkg = {
|
|
2850
|
-
name: slugStem(name, "wod-wiki-feed"),
|
|
2851
|
-
version: "0.1.0",
|
|
2852
|
-
private: true,
|
|
2853
|
-
...description ? { description } : {},
|
|
2854
|
-
...repositoryUrl ? { repository: { type: "git", url: repositoryUrl } } : {},
|
|
2855
|
-
scripts: {
|
|
2856
|
-
build: "wod build . --output dist"
|
|
2857
|
-
},
|
|
2858
|
-
devDependencies: {
|
|
2859
|
-
"@bitcobblers/wod-wiki-tools": `^${VERSION}`
|
|
2860
|
-
}
|
|
2861
|
-
};
|
|
2862
|
-
return JSON.stringify(pkg, null, 2) + "\n";
|
|
2863
|
-
}
|
|
2864
|
-
function repoReadmeMarkdown(name, description) {
|
|
2865
|
-
return `# ${name}
|
|
2866
|
-
|
|
2867
|
-
${description ?? "A WOD Wiki workout feed compiled from authored Markdown notes and optional companion JSONL session logs."}
|
|
2868
|
-
|
|
2869
|
-
## Layout
|
|
2870
|
-
|
|
2871
|
-
- \`markdown/notebooks/<slug>/*.md\` \u2014 Canonical workout & note Markdown with YAML frontmatter.
|
|
2872
|
-
- \`markdown/notebooks/<slug>/*.jsonl\` \u2014 Optional companion Session, BlockRevision, and EventRecord telemetry (present only for Sessions explicitly marked public).
|
|
2873
|
-
- \`dist/\` \u2014 Pre-compiled static Seed artifacts (\`manifest.json\`, \`indexes/\`, \`chunks/\`, \`index.html\`), ready for static hosting or rebuilt on push via GitHub Actions.
|
|
2874
|
-
`;
|
|
2875
|
-
}
|
|
2876
|
-
async function compileSeedRowForNote(params) {
|
|
2877
|
-
const {
|
|
2878
|
-
notePath,
|
|
2879
|
-
content,
|
|
2880
|
-
title,
|
|
2881
|
-
createdAt,
|
|
2882
|
-
routeId,
|
|
2883
|
-
sourceId,
|
|
2884
|
-
publicSessions,
|
|
2885
|
-
eventsBySession,
|
|
2886
|
-
revisionsByKey,
|
|
2887
|
-
referenceIndex
|
|
2888
|
-
} = params;
|
|
2889
|
-
const uuid = await seedNoteId(notePath);
|
|
2890
|
-
let ordinal = 0;
|
|
2891
|
-
const blocks = reconcileNoteBlocks(content, {
|
|
2892
|
-
sourceRevision: 1,
|
|
2893
|
-
registeredWidgets: SEED_REGISTERED_WIDGETS,
|
|
2894
|
-
createId: () => `seed:${notePath}:${ordinal++}`
|
|
2895
|
-
});
|
|
2896
|
-
const sections = parseDocumentSections(content, { registeredWidgets: SEED_REGISTERED_WIDGETS });
|
|
2897
|
-
const blockIndex = Object.values(blocks).map((block, position) => {
|
|
2898
|
-
const section = sections.find((s) => s.from === block.from && s.to === block.to);
|
|
2899
|
-
const fingerprint = block.kind === "wod" ? blockContentId(section?.scriptBlock?.content ?? content.slice(block.from, block.to)) : void 0;
|
|
2900
|
-
return {
|
|
2901
|
-
id: `${uuid}:${block.id}`,
|
|
2902
|
-
noteId: uuid,
|
|
2903
|
-
blockId: block.id,
|
|
2904
|
-
blockVersion: 1,
|
|
2905
|
-
sourceRevision: 1,
|
|
2906
|
-
from: block.from,
|
|
2907
|
-
to: block.to,
|
|
2908
|
-
position,
|
|
2909
|
-
dataType: block.kind,
|
|
2910
|
-
...fingerprint ? { blockContentId: fingerprint } : {},
|
|
2911
|
-
rawContent: content.slice(block.from, block.to),
|
|
2912
|
-
noteTitle: title,
|
|
2913
|
-
createdAt,
|
|
2914
|
-
isStatic: true,
|
|
2915
|
-
...sourceId ? { sourceId } : {},
|
|
2916
|
-
sourcePath: notePath,
|
|
2917
|
-
...routeId ? { routeId } : {}
|
|
2918
|
-
};
|
|
2919
|
-
});
|
|
2920
|
-
const blockEfforts = [];
|
|
2921
|
-
const blockEquipment = [];
|
|
2922
|
-
for (const proj of blockIndex) {
|
|
2923
|
-
if (proj.dataType !== "wod" || !proj.rawContent) continue;
|
|
2924
|
-
const sec = parseDocumentSections(proj.rawContent, { registeredWidgets: SEED_REGISTERED_WIDGETS }).find(
|
|
2925
|
-
(s) => s.scriptBlock
|
|
2926
|
-
);
|
|
2927
|
-
const parsed = parseScript(sec?.scriptBlock?.content ?? proj.rawContent, { references: referenceIndex });
|
|
2928
|
-
const refs = extractStatementRefs(parsed.statements);
|
|
2929
|
-
const seenEfforts = /* @__PURE__ */ new Set();
|
|
2930
|
-
for (const rawSlug of refs.efforts) {
|
|
2931
|
-
const canonical = referenceIndex.resolveEffort(rawSlug)?.slug;
|
|
2932
|
-
if (!canonical || seenEfforts.has(canonical)) continue;
|
|
2933
|
-
seenEfforts.add(canonical);
|
|
2934
|
-
blockEfforts.push({
|
|
2935
|
-
id: `${proj.id}:${canonical}`,
|
|
2936
|
-
noteId: uuid,
|
|
2937
|
-
blockId: proj.blockId,
|
|
2938
|
-
blockContentId: proj.blockContentId,
|
|
2939
|
-
effortSlug: canonical,
|
|
2940
|
-
isStatic: true,
|
|
2941
|
-
sourcePath: notePath,
|
|
2942
|
-
createdAt
|
|
2943
|
-
});
|
|
2944
|
-
}
|
|
2945
|
-
const seenEquipment = /* @__PURE__ */ new Set();
|
|
2946
|
-
for (const rawSlug of refs.equipment) {
|
|
2947
|
-
const canonical = referenceIndex.resolveEquipment(rawSlug)?.slug;
|
|
2948
|
-
if (!canonical || seenEquipment.has(canonical)) continue;
|
|
2949
|
-
seenEquipment.add(canonical);
|
|
2950
|
-
blockEquipment.push({
|
|
2951
|
-
id: `${proj.id}:${canonical}`,
|
|
2952
|
-
noteId: uuid,
|
|
2953
|
-
blockId: proj.blockId,
|
|
2954
|
-
blockContentId: proj.blockContentId,
|
|
2955
|
-
equipmentSlug: canonical,
|
|
2956
|
-
isStatic: true,
|
|
2957
|
-
sourcePath: notePath,
|
|
2958
|
-
createdAt
|
|
2959
|
-
});
|
|
2960
|
-
}
|
|
2961
|
-
}
|
|
2962
|
-
const wodProjections = blockIndex.filter((b) => b.dataType === "wod");
|
|
2963
|
-
const remappedSessions = [];
|
|
2964
|
-
const remappedEvents = [];
|
|
2965
|
-
const remappedRevisions = [];
|
|
2966
|
-
const seenRevKeys = /* @__PURE__ */ new Set();
|
|
2967
|
-
for (const s of publicSessions) {
|
|
2968
|
-
const matchedProj = wodProjections.find((p) => p.blockContentId && p.blockContentId === s.blockContentId) ?? wodProjections[0];
|
|
2969
|
-
if (!matchedProj || !matchedProj.blockContentId) continue;
|
|
2970
|
-
const mappedSession = {
|
|
2971
|
-
...s,
|
|
2972
|
-
noteId: uuid,
|
|
2973
|
-
blockId: matchedProj.blockId,
|
|
2974
|
-
blockVersion: 1,
|
|
2975
|
-
blockContentId: matchedProj.blockContentId,
|
|
2976
|
-
public: true
|
|
2977
|
-
};
|
|
2978
|
-
remappedSessions.push(mappedSession);
|
|
2979
|
-
const revKey = `${s.noteId}\0${s.blockId}\0${s.blockVersion}`;
|
|
2980
|
-
const origRev = revisionsByKey.get(revKey);
|
|
2981
|
-
const targetRevKey = `${uuid}\0${matchedProj.blockId}\x001`;
|
|
2982
|
-
if (!seenRevKeys.has(targetRevKey)) {
|
|
2983
|
-
seenRevKeys.add(targetRevKey);
|
|
2984
|
-
remappedRevisions.push({
|
|
2985
|
-
noteId: uuid,
|
|
2986
|
-
blockId: matchedProj.blockId,
|
|
2987
|
-
version: 1,
|
|
2988
|
-
kind: "wod",
|
|
2989
|
-
rawContent: matchedProj.rawContent,
|
|
2990
|
-
savedAt: origRev?.savedAt ?? s.createdAt,
|
|
2991
|
-
dialect: blocks[matchedProj.blockId]?.dialect ?? origRev?.dialect ?? "time",
|
|
2992
|
-
...blocks[matchedProj.blockId]?.sport ? { sport: blocks[matchedProj.blockId].sport } : {}
|
|
2993
|
-
});
|
|
2994
|
-
}
|
|
2995
|
-
for (const ev of eventsBySession.get(s.id) ?? []) {
|
|
2996
|
-
remappedEvents.push({
|
|
2997
|
-
...ev,
|
|
2998
|
-
noteId: uuid,
|
|
2999
|
-
blockId: matchedProj.blockId,
|
|
3000
|
-
blockVersion: 1,
|
|
3001
|
-
blockContentId: matchedProj.blockContentId
|
|
3002
|
-
});
|
|
3003
|
-
}
|
|
3004
|
-
}
|
|
3005
|
-
const telemetry = remappedSessions.length > 0 ? { sessions: remappedSessions, events: remappedEvents } : void 0;
|
|
3006
|
-
const companionBundle = remappedSessions.length > 0 ? {
|
|
3007
|
-
revisions: remappedRevisions,
|
|
3008
|
-
sessions: remappedSessions,
|
|
3009
|
-
events: remappedEvents
|
|
3010
|
-
} : void 0;
|
|
3011
|
-
const row = {
|
|
3012
|
-
path: notePath,
|
|
3013
|
-
content,
|
|
3014
|
-
blocks,
|
|
3015
|
-
blockIndex,
|
|
3016
|
-
blockEfforts,
|
|
3017
|
-
blockEquipment,
|
|
3018
|
-
uuid,
|
|
3019
|
-
commit: "",
|
|
3020
|
-
version: 1,
|
|
3021
|
-
...telemetry ? { telemetry } : {}
|
|
3022
|
-
};
|
|
3023
|
-
return { row, uuid, companionBundle };
|
|
3024
|
-
}
|
|
3025
|
-
async function collectPublicStorageState(storage, options = {}) {
|
|
3026
|
-
let allLinks = [];
|
|
3027
|
-
try {
|
|
3028
|
-
allLinks = await storage.readonly("notebook_links").getAll();
|
|
3029
|
-
} catch {
|
|
3030
|
-
}
|
|
3031
|
-
const [allNotes, allSessions, allEvents, allRevisions, efforts, equipment, storedMeta] = await Promise.all([
|
|
3032
|
-
storage.readonly("notes").getAll(),
|
|
3033
|
-
storage.readonly("sessions").getAll(),
|
|
3034
|
-
storage.readonly("events").getAll(),
|
|
3035
|
-
storage.readonly("block_revisions").getAll(),
|
|
3036
|
-
storage.readonly("efforts").getAll(),
|
|
3037
|
-
storage.readonly("equipment").getAll(),
|
|
3038
|
-
storage.readonly("meta").get(PUBLISHED_FEED_META_KEY)
|
|
3039
|
-
]);
|
|
3040
|
-
const notesById = new Map(allNotes.map((n) => [n.id, n]));
|
|
3041
|
-
const landingsBySlug = /* @__PURE__ */ new Map();
|
|
3042
|
-
for (const n of allNotes) {
|
|
3043
|
-
if (isPublishableNotebookLanding(n)) {
|
|
3044
|
-
landingsBySlug.set(notebookSlugFromId$1(n.id), n);
|
|
3045
|
-
}
|
|
3046
|
-
}
|
|
3047
|
-
const filterSlug = options.notebookSlug ? notebookSlugFromId$1(options.notebookSlug) : void 0;
|
|
3048
|
-
const notebooks = /* @__PURE__ */ new Map();
|
|
3049
|
-
for (const [slug, landing] of landingsBySlug.entries()) {
|
|
3050
|
-
if (filterSlug && slug !== filterSlug) continue;
|
|
3051
|
-
const isPublic = landing.public === true || filterSlug === slug && options.includePrivateWhenFiltered === true;
|
|
3052
|
-
if (!isPublic) continue;
|
|
3053
|
-
const fm = readFrontmatterMeta(landing.rawContent);
|
|
3054
|
-
const desc = typeof fm["description"] === "string" ? fm["description"].replace(/^"|"$/g, "") : void 0;
|
|
3055
|
-
notebooks.set(slug, {
|
|
3056
|
-
landing,
|
|
3057
|
-
label: landing.title || slug,
|
|
3058
|
-
description: desc,
|
|
3059
|
-
notes: []
|
|
3060
|
-
});
|
|
3061
|
-
}
|
|
3062
|
-
const noteLinkSlugsByNoteId = /* @__PURE__ */ new Map();
|
|
3063
|
-
for (const link of allLinks) {
|
|
3064
|
-
if (link.targetKind !== "note") continue;
|
|
3065
|
-
const set = noteLinkSlugsByNoteId.get(link.noteId) ?? /* @__PURE__ */ new Set();
|
|
3066
|
-
set.add(notebookSlugFromId$1(link.notebookId));
|
|
3067
|
-
noteLinkSlugsByNoteId.set(link.noteId, set);
|
|
3068
|
-
}
|
|
3069
|
-
for (const note of allNotes) {
|
|
3070
|
-
if (note.id.startsWith("notebook/") && note.notebookId === note.id) continue;
|
|
3071
|
-
if (isPublishableNotebookLanding(note)) continue;
|
|
3072
|
-
if (note.feedOrigin === "feed" || note.seedOrigin === "seed") {
|
|
3073
|
-
if (!filterSlug || !options.includePrivateWhenFiltered) continue;
|
|
3074
|
-
}
|
|
3075
|
-
const candidateSlugs = /* @__PURE__ */ new Set();
|
|
3076
|
-
const noteFm = readFrontmatterMeta(note.rawContent);
|
|
3077
|
-
const fmNotebook = (typeof noteFm["notebook"] === "string" ? noteFm["notebook"] : void 0) ?? (typeof noteFm["catalog"] === "string" ? noteFm["catalog"] : void 0);
|
|
3078
|
-
if (fmNotebook) candidateSlugs.add(notebookSlugFromId$1(fmNotebook));
|
|
3079
|
-
for (const nbId of notebooksOfItem(note)) {
|
|
3080
|
-
candidateSlugs.add(notebookSlugFromId$1(nbId));
|
|
3081
|
-
}
|
|
3082
|
-
if (note.sourceId) {
|
|
3083
|
-
const srcSlug = notebookSlugOfSourceId(note.sourceId);
|
|
3084
|
-
if (srcSlug) candidateSlugs.add(srcSlug);
|
|
3085
|
-
}
|
|
3086
|
-
for (const linkedSlug of noteLinkSlugsByNoteId.get(note.id) ?? []) {
|
|
3087
|
-
candidateSlugs.add(linkedSlug);
|
|
3088
|
-
}
|
|
3089
|
-
for (const slug of candidateSlugs) {
|
|
3090
|
-
if (!slug || isNonPublishableNotebook(slug)) continue;
|
|
3091
|
-
if (filterSlug && slug !== filterSlug) continue;
|
|
3092
|
-
let group = notebooks.get(slug);
|
|
3093
|
-
if (!group && options.includePrivateWhenFiltered) {
|
|
3094
|
-
group = { label: slug, notes: [] };
|
|
3095
|
-
notebooks.set(slug, group);
|
|
3096
|
-
}
|
|
3097
|
-
if (!group) continue;
|
|
3098
|
-
if (!group.notes.some((existing) => existing.id === note.id)) {
|
|
3099
|
-
group.notes.push(note);
|
|
3100
|
-
}
|
|
3101
|
-
}
|
|
3102
|
-
}
|
|
3103
|
-
for (const group of notebooks.values()) {
|
|
3104
|
-
group.notes.sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
|
|
3105
|
-
}
|
|
3106
|
-
const publicSessionsByNote = /* @__PURE__ */ new Map();
|
|
3107
|
-
const includedSessionIds = /* @__PURE__ */ new Set();
|
|
3108
|
-
for (const s of allSessions) {
|
|
3109
|
-
if (s.public !== true) continue;
|
|
3110
|
-
const list = publicSessionsByNote.get(s.noteId) ?? [];
|
|
3111
|
-
list.push(s);
|
|
3112
|
-
publicSessionsByNote.set(s.noteId, list);
|
|
3113
|
-
includedSessionIds.add(s.id);
|
|
3114
|
-
}
|
|
3115
|
-
for (const list of publicSessionsByNote.values()) {
|
|
3116
|
-
list.sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
|
|
3117
|
-
}
|
|
3118
|
-
const eventsBySession = /* @__PURE__ */ new Map();
|
|
3119
|
-
for (const ev of allEvents) {
|
|
3120
|
-
if (!includedSessionIds.has(ev.resultId)) continue;
|
|
3121
|
-
const list = eventsBySession.get(ev.resultId) ?? [];
|
|
3122
|
-
list.push(ev);
|
|
3123
|
-
eventsBySession.set(ev.resultId, list);
|
|
3124
|
-
}
|
|
3125
|
-
for (const list of eventsBySession.values()) {
|
|
3126
|
-
list.sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
|
|
3127
|
-
}
|
|
3128
|
-
const revisionsByKey = /* @__PURE__ */ new Map();
|
|
3129
|
-
for (const rev of allRevisions) {
|
|
3130
|
-
revisionsByKey.set(`${rev.noteId}\0${rev.blockId}\0${rev.version}`, rev);
|
|
3131
|
-
}
|
|
3132
|
-
const isCheckpoint = (v) => typeof v === "object" && v !== null && "key" in v && v.key === PUBLISHED_FEED_META_KEY;
|
|
3133
|
-
const storedCheckpoint = isCheckpoint(storedMeta) ? storedMeta : void 0;
|
|
3134
|
-
return {
|
|
3135
|
-
notebooks,
|
|
3136
|
-
publicSessionsByNote,
|
|
3137
|
-
eventsBySession,
|
|
3138
|
-
revisionsByKey,
|
|
3139
|
-
efforts,
|
|
3140
|
-
equipment,
|
|
3141
|
-
notesById,
|
|
3142
|
-
storedCheckpoint
|
|
3143
|
-
};
|
|
3144
|
-
}
|
|
3145
|
-
async function publishFeedFromStorage(storage, tree, options = {}) {
|
|
3146
|
-
const t0 = Date.now();
|
|
3147
|
-
const layout = options.layout ?? "feed";
|
|
3148
|
-
const state = await collectPublicStorageState(storage, options);
|
|
3149
|
-
if (state.notebooks.size === 0) {
|
|
3150
|
-
throw new Error("No public notebooks found to publish. Mark at least one user-owned notebook as Public first.");
|
|
3151
|
-
}
|
|
3152
|
-
const globalCatalog = await resolveScopedPropertyCatalog(storage, { mode: "custom-runtime" });
|
|
3153
|
-
const mergedEffortsBySlug = new Map(state.efforts.map((e) => [e.slug, e]));
|
|
3154
|
-
for (const eff of globalCatalog.efforts) mergedEffortsBySlug.set(eff.slug, eff);
|
|
3155
|
-
const mergedEquipBySlug = new Map(state.equipment.map((e) => [e.slug, e]));
|
|
3156
|
-
for (const eq of globalCatalog.equipment) mergedEquipBySlug.set(eq.slug, eq);
|
|
3157
|
-
const referenceIndex = createReferenceIndex({
|
|
3158
|
-
efforts: [...mergedEffortsBySlug.values()],
|
|
3159
|
-
equipment: [...mergedEquipBySlug.values()]
|
|
3160
|
-
});
|
|
3161
|
-
const nextVersion = options.version ?? (state.storedCheckpoint?.version ?? 0) + 1;
|
|
3162
|
-
const builtAt = options.builtAt ?? (/* @__PURE__ */ new Date()).toISOString();
|
|
3163
|
-
const artifactPrefix = layout === "repository" ? "dist/" : "";
|
|
3164
|
-
const manifestChunks = [];
|
|
3165
|
-
const manifestNotebooks = [];
|
|
3166
|
-
const landingNotebooks = [];
|
|
3167
|
-
const referencedUserEfforts = /* @__PURE__ */ new Set();
|
|
3168
|
-
const referencedUserEquipment = /* @__PURE__ */ new Set();
|
|
3169
|
-
let totalNotes = 0;
|
|
3170
|
-
let totalPublicSessions = 0;
|
|
3171
|
-
const sortedSlugs = [...state.notebooks.keys()].sort();
|
|
3172
|
-
for (const notebookSlug of sortedSlugs) {
|
|
3173
|
-
const group = state.notebooks.get(notebookSlug);
|
|
3174
|
-
const chunkId = `notebook.${notebookSlug}`;
|
|
3175
|
-
const usedStems = /* @__PURE__ */ new Set();
|
|
3176
|
-
const rows = [];
|
|
3177
|
-
const records = [];
|
|
3178
|
-
const landingNotes = [];
|
|
3179
|
-
const nbReferencedEfforts = /* @__PURE__ */ new Set();
|
|
3180
|
-
const nbReferencedEquipment = /* @__PURE__ */ new Set();
|
|
3181
|
-
const nbReferencedTags = /* @__PURE__ */ new Set();
|
|
3182
|
-
if (layout === "repository") {
|
|
3183
|
-
const readmeMd = group.landing ? group.landing.rawContent : `# ${group.label}
|
|
3184
|
-
|
|
3185
|
-
${group.description ?? ""}
|
|
3186
|
-
`;
|
|
3187
|
-
await tree.write(`markdown/notebooks/${notebookSlug}/README.md`, encodeUtf8(readmeMd));
|
|
3188
|
-
}
|
|
3189
|
-
for (const note of group.notes) {
|
|
3190
|
-
let baseStem = slugStem(note.title || note.id, "note");
|
|
3191
|
-
if (baseStem.toLowerCase() === "readme") baseStem = "note-readme";
|
|
3192
|
-
let stem = baseStem;
|
|
3193
|
-
let suffix = 2;
|
|
3194
|
-
while (usedStems.has(stem)) {
|
|
3195
|
-
stem = `${baseStem}-${suffix++}`;
|
|
3196
|
-
}
|
|
3197
|
-
usedStems.add(stem);
|
|
3198
|
-
const notePath = `markdown/notebooks/${notebookSlug}/${stem}.md`;
|
|
3199
|
-
const portableMd = composeNoteMarkdown({
|
|
3200
|
-
...note,
|
|
3201
|
-
notebookId: `notebook/${notebookSlug}`
|
|
3202
|
-
});
|
|
3203
|
-
const contentForSeed = layout === "repository" ? portableMd : note.rawContent;
|
|
3204
|
-
const targetNbId = toNotebookId$1(notebookSlug);
|
|
3205
|
-
const allPublicForNote = state.publicSessionsByNote.get(note.id) ?? [];
|
|
3206
|
-
const publicSessions = allPublicForNote.filter((sess) => {
|
|
3207
|
-
const userPinned = (sess.notebookIds ?? []).map((id) => toNotebookId$1(id)).filter((id) => !isNonPublishableNotebook(id));
|
|
3208
|
-
return userPinned.length === 0 || userPinned.includes(targetNbId);
|
|
3209
|
-
});
|
|
3210
|
-
totalPublicSessions += publicSessions.length;
|
|
3211
|
-
const { row, uuid, companionBundle } = await compileSeedRowForNote({
|
|
3212
|
-
notePath,
|
|
3213
|
-
content: contentForSeed,
|
|
3214
|
-
title: note.title || stem,
|
|
3215
|
-
createdAt: note.date ?? note.createdAt,
|
|
3216
|
-
routeId: `${notebookSlug}/${stem}`,
|
|
3217
|
-
sourceId: `notebook:${notebookSlug}/${stem}`,
|
|
3218
|
-
publicSessions,
|
|
3219
|
-
eventsBySession: state.eventsBySession,
|
|
3220
|
-
revisionsByKey: state.revisionsByKey,
|
|
3221
|
-
referenceIndex
|
|
3222
|
-
});
|
|
3223
|
-
for (const eff of row.blockEfforts) {
|
|
3224
|
-
referencedUserEfforts.add(eff.effortSlug);
|
|
3225
|
-
nbReferencedEfforts.add(eff.effortSlug);
|
|
3226
|
-
}
|
|
3227
|
-
for (const eq of row.blockEquipment) {
|
|
3228
|
-
referencedUserEquipment.add(eq.equipmentSlug);
|
|
3229
|
-
nbReferencedEquipment.add(eq.equipmentSlug);
|
|
3230
|
-
}
|
|
3231
|
-
for (const t of extractTypedTags(note.rawContent)) {
|
|
3232
|
-
nbReferencedTags.add(t.label);
|
|
3233
|
-
}
|
|
3234
|
-
for (const m of note.rawContent.matchAll(/#([a-z0-9][a-z0-9-]*)/gi)) {
|
|
3235
|
-
if (m[1]) nbReferencedTags.add(m[1].toLowerCase());
|
|
3236
|
-
}
|
|
3237
|
-
rows.push(row);
|
|
3238
|
-
await tree.write(notePath, encodeUtf8(portableMd));
|
|
3239
|
-
const recordRelPath = notePath.replace(/\.md$/, ".json");
|
|
3240
|
-
const recordBytes = encodeUtf8(JSON.stringify(row, null, 2));
|
|
3241
|
-
await tree.write(`${artifactPrefix}${recordRelPath}`, recordBytes);
|
|
3242
|
-
if (companionBundle) {
|
|
3243
|
-
const jsonlText = serializeNoteBundleToJsonl(companionBundle) + "\n";
|
|
3244
|
-
await tree.write(notePath.replace(/\.md$/, ".jsonl"), encodeUtf8(jsonlText));
|
|
3245
|
-
if (artifactPrefix) {
|
|
3246
|
-
await tree.write(`${artifactPrefix}${notePath.replace(/\.md$/, ".jsonl")}`, encodeUtf8(jsonlText));
|
|
3247
|
-
}
|
|
3248
|
-
}
|
|
3249
|
-
records.push({
|
|
3250
|
-
uuid,
|
|
3251
|
-
path: notePath,
|
|
3252
|
-
recordPath: recordRelPath,
|
|
3253
|
-
commit: "",
|
|
3254
|
-
version: note.sourceRevision ?? 1,
|
|
3255
|
-
sha256: await sha256HexAsync(recordBytes),
|
|
3256
|
-
title: note.title || stem,
|
|
3257
|
-
...note.date !== void 0 ? { date: note.date } : {}
|
|
3258
|
-
});
|
|
3259
|
-
landingNotes.push({
|
|
3260
|
-
title: note.title || stem,
|
|
3261
|
-
path: notePath,
|
|
3262
|
-
date: note.date,
|
|
3263
|
-
recordPath: recordRelPath,
|
|
3264
|
-
content: note.rawContent,
|
|
3265
|
-
publicSessions: publicSessions.length
|
|
3266
|
-
});
|
|
3267
|
-
}
|
|
3268
|
-
assertSeedRows(rows);
|
|
3269
|
-
const chunkBytes = encodeUtf8(JSON.stringify(rows));
|
|
3270
|
-
const chunkSha = await sha256HexAsync(chunkBytes);
|
|
3271
|
-
const chunkRelPath = `chunks/${chunkId}.${chunkSha.slice(0, 8)}.json`;
|
|
3272
|
-
await tree.write(`${artifactPrefix}${chunkRelPath}`, chunkBytes);
|
|
3273
|
-
manifestChunks.push({
|
|
3274
|
-
id: chunkId,
|
|
3275
|
-
path: chunkRelPath,
|
|
3276
|
-
sha256: chunkSha,
|
|
3277
|
-
bytes: chunkBytes.byteLength,
|
|
3278
|
-
count: rows.length,
|
|
3279
|
-
kind: "notes"
|
|
3280
|
-
});
|
|
3281
|
-
totalNotes += rows.length;
|
|
3282
|
-
await promoteReferencedOverridesToNotebook(storage, {
|
|
3283
|
-
notebookId: `notebook/${notebookSlug}`,
|
|
3284
|
-
effortSlugs: nbReferencedEfforts,
|
|
3285
|
-
equipmentSlugs: nbReferencedEquipment,
|
|
3286
|
-
tagSlugs: nbReferencedTags
|
|
3287
|
-
});
|
|
3288
|
-
const indexPath = `indexes/notebooks/${chunkId}.json`;
|
|
3289
|
-
const summary = {
|
|
3290
|
-
notebookId: chunkId,
|
|
3291
|
-
label: group.label,
|
|
3292
|
-
category: notebookSlugForChunkId(chunkId),
|
|
3293
|
-
indexPath,
|
|
3294
|
-
version: nextVersion,
|
|
3295
|
-
commit: "",
|
|
3296
|
-
updatedAt: builtAt,
|
|
3297
|
-
builtAt,
|
|
3298
|
-
sha256: chunkSha,
|
|
3299
|
-
bytes: chunkBytes.byteLength,
|
|
3300
|
-
count: rows.length
|
|
3301
|
-
};
|
|
3302
|
-
const notebookIndex = {
|
|
3303
|
-
...summary,
|
|
3304
|
-
records
|
|
3305
|
-
};
|
|
3306
|
-
assertNotebookIndex(notebookIndex);
|
|
3307
|
-
await tree.write(`${artifactPrefix}${indexPath}`, encodeUtf8(JSON.stringify(notebookIndex, null, 2) + "\n"));
|
|
3308
|
-
manifestNotebooks.push(summary);
|
|
3309
|
-
landingNotebooks.push({
|
|
3310
|
-
id: chunkId,
|
|
3311
|
-
label: group.label,
|
|
3312
|
-
notes: landingNotes
|
|
3313
|
-
});
|
|
3314
|
-
}
|
|
3315
|
-
const promotedOverrides = await listScopedPropertyOverrides(storage);
|
|
3316
|
-
const overrideEffortBySlug = /* @__PURE__ */ new Map();
|
|
3317
|
-
const overrideEquipBySlug = /* @__PURE__ */ new Map();
|
|
3318
|
-
for (const ov of promotedOverrides) {
|
|
3319
|
-
if (ov.seedOrigin === "seed") continue;
|
|
3320
|
-
if (ov.kind === "effort" && ov.payload) {
|
|
3321
|
-
overrideEffortBySlug.set(ov.slug, { eff: ov.payload, md: ov.rawContent });
|
|
3322
|
-
} else if (ov.kind === "equipment" && ov.payload) {
|
|
3323
|
-
overrideEquipBySlug.set(ov.slug, { eq: ov.payload, md: ov.rawContent });
|
|
3324
|
-
}
|
|
3325
|
-
}
|
|
3326
|
-
const userEffortMap = /* @__PURE__ */ new Map();
|
|
3327
|
-
for (const e of state.efforts) {
|
|
3328
|
-
if (e.registrySource !== "bundled" && referencedUserEfforts.has(e.slug)) {
|
|
3329
|
-
const owner = e.ownerNoteId ? state.notesById.get(e.ownerNoteId) : void 0;
|
|
3330
|
-
userEffortMap.set(e.slug, { eff: e, md: owner?.rawContent ?? effortToMarkdown(e) });
|
|
3331
|
-
}
|
|
3332
|
-
}
|
|
3333
|
-
for (const slug of referencedUserEfforts) {
|
|
3334
|
-
const ov = overrideEffortBySlug.get(slug);
|
|
3335
|
-
if (ov) userEffortMap.set(slug, ov);
|
|
3336
|
-
}
|
|
3337
|
-
if (userEffortMap.size > 0) {
|
|
3338
|
-
const effortRows = [];
|
|
3339
|
-
for (const { eff, md } of [...userEffortMap.values()].sort((a, b) => a.eff.slug < b.eff.slug ? -1 : 1)) {
|
|
3340
|
-
const effPath = `markdown/efforts/${eff.slug}.md`;
|
|
3341
|
-
await tree.write(effPath, encodeUtf8(md));
|
|
3342
|
-
const { row } = await compileSeedRowForNote({
|
|
3343
|
-
notePath: effPath,
|
|
3344
|
-
content: md,
|
|
3345
|
-
title: eff.label,
|
|
3346
|
-
createdAt: 0,
|
|
3347
|
-
sourceId: "efforts",
|
|
3348
|
-
publicSessions: [],
|
|
3349
|
-
eventsBySession: state.eventsBySession,
|
|
3350
|
-
revisionsByKey: state.revisionsByKey,
|
|
3351
|
-
referenceIndex
|
|
3352
|
-
});
|
|
3353
|
-
effortRows.push(row);
|
|
3354
|
-
}
|
|
3355
|
-
assertSeedRows(effortRows);
|
|
3356
|
-
const bytes = encodeUtf8(JSON.stringify(effortRows));
|
|
3357
|
-
const sha = await sha256HexAsync(bytes);
|
|
3358
|
-
const rel = `chunks/${EFFORTS_CHUNK_ID}.${sha.slice(0, 8)}.json`;
|
|
3359
|
-
await tree.write(`${artifactPrefix}${rel}`, bytes);
|
|
3360
|
-
manifestChunks.push({ id: EFFORTS_CHUNK_ID, path: rel, sha256: sha, bytes: bytes.byteLength, count: effortRows.length });
|
|
3361
|
-
}
|
|
3362
|
-
const userEquipMap = /* @__PURE__ */ new Map();
|
|
3363
|
-
for (const eq of state.equipment) {
|
|
3364
|
-
if (eq.registrySource !== "bundled" && referencedUserEquipment.has(eq.slug)) {
|
|
3365
|
-
const owner = eq.ownerNoteId ? state.notesById.get(eq.ownerNoteId) : void 0;
|
|
3366
|
-
userEquipMap.set(eq.slug, { eq, md: owner?.rawContent ?? equipmentToMarkdown(eq) });
|
|
3367
|
-
}
|
|
3368
|
-
}
|
|
3369
|
-
for (const slug of referencedUserEquipment) {
|
|
3370
|
-
const ov = overrideEquipBySlug.get(slug);
|
|
3371
|
-
if (ov) userEquipMap.set(slug, ov);
|
|
3372
|
-
}
|
|
3373
|
-
if (userEquipMap.size > 0) {
|
|
3374
|
-
const eqRows = [];
|
|
3375
|
-
for (const { eq, md } of [...userEquipMap.values()].sort((a, b) => a.eq.slug < b.eq.slug ? -1 : 1)) {
|
|
3376
|
-
const eqPath = `markdown/equipment/${eq.slug}.md`;
|
|
3377
|
-
await tree.write(eqPath, encodeUtf8(md));
|
|
3378
|
-
const { row } = await compileSeedRowForNote({
|
|
3379
|
-
notePath: eqPath,
|
|
3380
|
-
content: md,
|
|
3381
|
-
title: eq.label,
|
|
3382
|
-
createdAt: 0,
|
|
3383
|
-
sourceId: "equipment",
|
|
3384
|
-
publicSessions: [],
|
|
3385
|
-
eventsBySession: state.eventsBySession,
|
|
3386
|
-
revisionsByKey: state.revisionsByKey,
|
|
3387
|
-
referenceIndex
|
|
3388
|
-
});
|
|
3389
|
-
eqRows.push(row);
|
|
3390
|
-
}
|
|
3391
|
-
assertSeedRows(eqRows);
|
|
3392
|
-
const bytes = encodeUtf8(JSON.stringify(eqRows));
|
|
3393
|
-
const sha = await sha256HexAsync(bytes);
|
|
3394
|
-
const rel = `chunks/${EQUIPMENT_CHUNK_ID}.${sha.slice(0, 8)}.json`;
|
|
3395
|
-
await tree.write(`${artifactPrefix}${rel}`, bytes);
|
|
3396
|
-
manifestChunks.push({ id: EQUIPMENT_CHUNK_ID, path: rel, sha256: sha, bytes: bytes.byteLength, count: eqRows.length });
|
|
3397
|
-
}
|
|
3398
|
-
const safeRepoUrl = options.repositoryUrl && /^https:\/\//.test(options.repositoryUrl) ? options.repositoryUrl : void 0;
|
|
3399
|
-
const feedName = options.name ?? "My Published Feed";
|
|
3400
|
-
const manifest = {
|
|
3401
|
-
name: feedName,
|
|
3402
|
-
...options.description ? { description: options.description } : {},
|
|
3403
|
-
...safeRepoUrl ? { repositoryUrl: safeRepoUrl } : {},
|
|
3404
|
-
schema: SEED_SCHEMA,
|
|
3405
|
-
version: nextVersion,
|
|
3406
|
-
versionLabel: `v${nextVersion}`,
|
|
3407
|
-
commit: "",
|
|
3408
|
-
builtAt,
|
|
3409
|
-
chunks: manifestChunks,
|
|
3410
|
-
notebooks: manifestNotebooks
|
|
3411
|
-
};
|
|
3412
|
-
assertSeedManifest(manifest);
|
|
3413
|
-
const totalMs = Math.max(1, Date.now() - t0);
|
|
3414
|
-
const landingHtml = renderFeedLandingHtml({
|
|
3415
|
-
manifest,
|
|
3416
|
-
totalMs,
|
|
3417
|
-
passMs: { scan: 0, blockIndex: 0, parseGate: 0, blockEfforts: 0, write: totalMs },
|
|
3418
|
-
fileCount: totalNotes,
|
|
3419
|
-
notebooks: landingNotebooks
|
|
3420
|
-
});
|
|
3421
|
-
await tree.write(`${artifactPrefix}index.html`, encodeUtf8(landingHtml));
|
|
3422
|
-
if (layout === "repository") {
|
|
3423
|
-
if (!await tree.stat("package.json")) {
|
|
3424
|
-
await tree.write("package.json", encodeUtf8(repoPackageJson(feedName, options.description, safeRepoUrl)));
|
|
3425
|
-
}
|
|
3426
|
-
if (!await tree.stat(".github/workflows/publish-feed.yml")) {
|
|
3427
|
-
await tree.write(".github/workflows/publish-feed.yml", encodeUtf8(repoWorkflowYaml()));
|
|
3428
|
-
}
|
|
3429
|
-
if (!await tree.stat("README.md")) {
|
|
3430
|
-
await tree.write("README.md", encodeUtf8(repoReadmeMarkdown(feedName, options.description)));
|
|
3431
|
-
}
|
|
3432
|
-
}
|
|
3433
|
-
const manifestBytes = encodeUtf8(JSON.stringify(manifest, null, 2) + "\n");
|
|
3434
|
-
const manifestSha256 = await sha256HexAsync(manifestBytes);
|
|
3435
|
-
await tree.write(`${artifactPrefix}manifest.json`, manifestBytes);
|
|
3436
|
-
const shouldCheckpoint = options.recordCheckpoint ?? (layout === "feed" && !options.notebookSlug);
|
|
3437
|
-
if (shouldCheckpoint) {
|
|
3438
|
-
const chunkShas = {};
|
|
3439
|
-
for (const c of manifestChunks) chunkShas[c.id] = c.sha256;
|
|
3440
|
-
const cp = {
|
|
3441
|
-
key: PUBLISHED_FEED_META_KEY,
|
|
3442
|
-
version: nextVersion,
|
|
3443
|
-
builtAt,
|
|
3444
|
-
manifestSha256,
|
|
3445
|
-
chunkShas
|
|
3446
|
-
};
|
|
3447
|
-
await storage.transaction(["meta"], "readwrite", async (tx) => {
|
|
3448
|
-
await tx.readwrite("meta").put(cp);
|
|
3449
|
-
});
|
|
3450
|
-
}
|
|
3451
|
-
return {
|
|
3452
|
-
manifest,
|
|
3453
|
-
notebooks: sortedSlugs,
|
|
3454
|
-
totalNotes,
|
|
3455
|
-
totalPublicSessions,
|
|
3456
|
-
manifestSha256
|
|
3457
|
-
};
|
|
3458
|
-
}
|
|
3459
|
-
async function checkUnpublishedFeedChanges(storage, currentTree, options = {}) {
|
|
3460
|
-
const state = await collectPublicStorageState(storage, options);
|
|
3461
|
-
const publicNotebooks = state.notebooks.size;
|
|
3462
|
-
let publicNotes = 0;
|
|
3463
|
-
let publicSessions = 0;
|
|
3464
|
-
for (const nb of state.notebooks.values()) {
|
|
3465
|
-
publicNotes += nb.notes.length;
|
|
3466
|
-
for (const n of nb.notes) {
|
|
3467
|
-
publicSessions += (state.publicSessionsByNote.get(n.id) ?? []).length;
|
|
3468
|
-
}
|
|
3469
|
-
}
|
|
3470
|
-
let priorChunkShas = state.storedCheckpoint?.chunkShas;
|
|
3471
|
-
let publishedVersion = state.storedCheckpoint?.version ?? null;
|
|
3472
|
-
let builtAt = state.storedCheckpoint?.builtAt ?? null;
|
|
3473
|
-
if (currentTree) {
|
|
3474
|
-
try {
|
|
3475
|
-
const raw = decodeUtf8(await currentTree.read("manifest.json"));
|
|
3476
|
-
const parsed = assertSeedManifest(JSON.parse(raw));
|
|
3477
|
-
publishedVersion = parsed.version;
|
|
3478
|
-
builtAt = parsed.builtAt;
|
|
3479
|
-
priorChunkShas = {};
|
|
3480
|
-
for (const c of parsed.chunks) priorChunkShas[c.id] = c.sha256;
|
|
3481
|
-
} catch {
|
|
3482
|
-
}
|
|
3483
|
-
}
|
|
3484
|
-
if (publicNotebooks === 0) {
|
|
3485
|
-
const hadPrior = priorChunkShas !== void 0 && Object.keys(priorChunkShas).length > 0;
|
|
3486
|
-
return {
|
|
3487
|
-
hasPublicContent: false,
|
|
3488
|
-
publishedVersion,
|
|
3489
|
-
builtAt,
|
|
3490
|
-
dirty: hadPrior,
|
|
3491
|
-
publicNotebooks: 0,
|
|
3492
|
-
publicNotes: 0,
|
|
3493
|
-
publicSessions: 0,
|
|
3494
|
-
changes: hadPrior ? Object.keys(priorChunkShas).map((id) => ({ notebookId: id, status: "removed" })) : []
|
|
3495
|
-
};
|
|
3496
|
-
}
|
|
3497
|
-
const scratch = new MemoryFeedTree();
|
|
3498
|
-
const compiled = await publishFeedFromStorage(storage, scratch, {
|
|
3499
|
-
...options,
|
|
3500
|
-
layout: "feed",
|
|
3501
|
-
version: publishedVersion ?? 1,
|
|
3502
|
-
builtAt: builtAt ?? "1970-01-01T00:00:00.000Z",
|
|
3503
|
-
recordCheckpoint: false
|
|
3504
|
-
});
|
|
3505
|
-
if (!priorChunkShas) {
|
|
3506
|
-
return {
|
|
3507
|
-
hasPublicContent: true,
|
|
3508
|
-
publishedVersion: null,
|
|
3509
|
-
builtAt: null,
|
|
3510
|
-
dirty: true,
|
|
3511
|
-
publicNotebooks,
|
|
3512
|
-
publicNotes,
|
|
3513
|
-
publicSessions,
|
|
3514
|
-
changes: compiled.manifest.chunks.map((c) => ({ notebookId: c.id, status: "added" }))
|
|
3515
|
-
};
|
|
3516
|
-
}
|
|
3517
|
-
const changes = [];
|
|
3518
|
-
const nextIds = /* @__PURE__ */ new Set();
|
|
3519
|
-
for (const c of compiled.manifest.chunks) {
|
|
3520
|
-
nextIds.add(c.id);
|
|
3521
|
-
if (!(c.id in priorChunkShas)) {
|
|
3522
|
-
changes.push({ notebookId: c.id, status: "added" });
|
|
3523
|
-
} else if (priorChunkShas[c.id] !== c.sha256) {
|
|
3524
|
-
changes.push({ notebookId: c.id, status: "modified" });
|
|
3525
|
-
}
|
|
3526
|
-
}
|
|
3527
|
-
for (const oldId of Object.keys(priorChunkShas)) {
|
|
3528
|
-
if (!nextIds.has(oldId)) {
|
|
3529
|
-
changes.push({ notebookId: oldId, status: "removed" });
|
|
3530
|
-
}
|
|
3531
|
-
}
|
|
3532
|
-
return {
|
|
3533
|
-
hasPublicContent: true,
|
|
3534
|
-
publishedVersion,
|
|
3535
|
-
builtAt,
|
|
3536
|
-
dirty: changes.length > 0,
|
|
3537
|
-
publicNotebooks,
|
|
3538
|
-
publicNotes,
|
|
3539
|
-
publicSessions,
|
|
3540
|
-
changes
|
|
3541
|
-
};
|
|
3542
|
-
}
|
|
3543
|
-
function makeNotebookLinkId(notebookId, targetKind, targetId) {
|
|
3544
|
-
return `${notebookId}:${targetKind}:${targetId}`;
|
|
3545
|
-
}
|
|
3546
|
-
function isPropertyDefinitionNoteId(noteId) {
|
|
3547
|
-
return noteId.startsWith("effort/") || noteId.startsWith("equipment/") || noteId.startsWith("t/");
|
|
3548
|
-
}
|
|
3549
|
-
function isNotebookLandingNote(note) {
|
|
3550
|
-
return note.id.startsWith("notebook/") && note.notebookId === note.id;
|
|
3551
|
-
}
|
|
3552
|
-
function baseUserMemberships(note) {
|
|
3553
|
-
if (note.seedOrigin === "seed" || note.feedOrigin === "feed") return [];
|
|
3554
|
-
if (isNotebookLandingNote(note) || isPropertyDefinitionNoteId(note.id)) return [];
|
|
3555
|
-
const base = ["notebook/journal"];
|
|
3556
|
-
if (note.type === "playground" || note.sourceId === "playground") {
|
|
3557
|
-
base.push("notebook/playground");
|
|
3558
|
-
}
|
|
3559
|
-
return base;
|
|
3560
|
-
}
|
|
3561
|
-
function dedupeNotebooks(ids) {
|
|
3562
|
-
const out = [];
|
|
3563
|
-
for (const raw of ids) {
|
|
3564
|
-
if (!raw || !raw.trim()) continue;
|
|
3565
|
-
const norm = toNotebookId$1(raw);
|
|
3566
|
-
if (!out.includes(norm)) out.push(norm);
|
|
3567
|
-
}
|
|
3568
|
-
return out;
|
|
3569
|
-
}
|
|
3570
|
-
async function assertWritableTargetNotebook(tx, notebookId) {
|
|
3571
|
-
if (isSystemReadOnlyNotebook(notebookId)) {
|
|
3572
|
-
throw new Error(`Notebook '${notebookId}' is read-only and cannot accept promoted notes.`);
|
|
3573
|
-
}
|
|
3574
|
-
const landing = await tx.readonly("notes").get(notebookId);
|
|
3575
|
-
if (landing && (landing.feedOrigin === "feed" || landing.seedOrigin === "seed")) {
|
|
3576
|
-
throw new Error(`Notebook '${notebookId}' is feed-delivered and read-only.`);
|
|
3577
|
-
}
|
|
3578
|
-
}
|
|
3579
|
-
async function ensureUserNotebookLanding(tx, notebookId, now) {
|
|
3580
|
-
if (isNonPublishableNotebook(notebookId)) return;
|
|
3581
|
-
const existing = await tx.readonly("notes").get(notebookId);
|
|
3582
|
-
if (existing) return;
|
|
3583
|
-
const slug = notebookSlugFromId$1(notebookId);
|
|
3584
|
-
const title = slug.split("-").filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(" ") || slug;
|
|
3585
|
-
await tx.readwrite("notes").put({
|
|
3586
|
-
id: notebookId,
|
|
3587
|
-
title,
|
|
3588
|
-
rawContent: `# ${title}
|
|
3589
|
-
`,
|
|
3590
|
-
sourceRevision: 1,
|
|
3591
|
-
blocks: {},
|
|
3592
|
-
createdAt: now,
|
|
3593
|
-
notebookId,
|
|
3594
|
-
seedOrigin: "user"
|
|
3595
|
-
});
|
|
3596
|
-
}
|
|
3597
|
-
async function createUserNotebookLanding(storage, rawName) {
|
|
3598
|
-
const trimmed = rawName.trim();
|
|
3599
|
-
let slug = trimmed.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "notebook";
|
|
3600
|
-
if (isNonPublishableNotebook(slug)) slug = `${slug}-user`;
|
|
3601
|
-
const nbId = toNotebookId$1(slug);
|
|
3602
|
-
await storage.transaction(["notes"], "readwrite", async (tx) => {
|
|
3603
|
-
const existing = await tx.readonly("notes").get(nbId);
|
|
3604
|
-
if (!existing) {
|
|
3605
|
-
await tx.readwrite("notes").put({
|
|
3606
|
-
id: nbId,
|
|
3607
|
-
title: trimmed || slug,
|
|
3608
|
-
rawContent: `# ${trimmed || slug}
|
|
3609
|
-
`,
|
|
3610
|
-
sourceRevision: 1,
|
|
3611
|
-
blocks: {},
|
|
3612
|
-
createdAt: Date.now(),
|
|
3613
|
-
notebookId: nbId,
|
|
3614
|
-
seedOrigin: "user"
|
|
3615
|
-
});
|
|
3616
|
-
}
|
|
3617
|
-
});
|
|
3618
|
-
return nbId;
|
|
3619
|
-
}
|
|
3620
|
-
async function promoteNoteToNotebooks(storage, input) {
|
|
3621
|
-
const requestedTargets = dedupeNotebooks(input.notebookIds);
|
|
3622
|
-
const now = Date.now();
|
|
3623
|
-
return storage.transaction(
|
|
3624
|
-
["notes", "sessions", "notebook_links", "block_revisions"],
|
|
3625
|
-
"readwrite",
|
|
3626
|
-
async (tx) => {
|
|
3627
|
-
const note = await tx.readonly("notes").get(input.noteId);
|
|
3628
|
-
if (!note) {
|
|
3629
|
-
throw new Error(`Note not found: ${input.noteId}`);
|
|
3630
|
-
}
|
|
3631
|
-
if (note.seedOrigin === "seed" || note.feedOrigin === "feed") {
|
|
3632
|
-
throw new Error(`Read-only Feed Note '${input.noteId}' must be cloned before promotion.`);
|
|
3633
|
-
}
|
|
3634
|
-
for (const target of requestedTargets) {
|
|
3635
|
-
if (target !== "notebook/journal" && target !== "notebook/playground") {
|
|
3636
|
-
await assertWritableTargetNotebook(tx, target);
|
|
3637
|
-
await ensureUserNotebookLanding(tx, target, now);
|
|
3638
|
-
}
|
|
3639
|
-
}
|
|
3640
|
-
const existingLinks = await tx.readonly("notebook_links").getAllFromIndex("by-note", note.id);
|
|
3641
|
-
const existingNoteLinks = existingLinks.filter((l) => l.targetKind === "note" && l.targetId === note.id).map((l) => toNotebookId$1(l.notebookId));
|
|
3642
|
-
const merged = dedupeNotebooks([
|
|
3643
|
-
...baseUserMemberships(note),
|
|
3644
|
-
...note.notebookIds ?? [],
|
|
3645
|
-
...note.notebookId ? [note.notebookId] : [],
|
|
3646
|
-
...existingNoteLinks,
|
|
3647
|
-
...requestedTargets
|
|
3648
|
-
]);
|
|
3649
|
-
const primaryUserNb = merged.find(
|
|
3650
|
-
(id) => id !== "notebook/journal" && id !== "notebook/playground"
|
|
3651
|
-
);
|
|
3652
|
-
const updatedNote = {
|
|
3653
|
-
...note,
|
|
3654
|
-
notebookIds: merged,
|
|
3655
|
-
...primaryUserNb ? { notebookId: primaryUserNb } : {}
|
|
3656
|
-
};
|
|
3657
|
-
await tx.readwrite("notes").put(updatedNote);
|
|
3658
|
-
const linkRows = merged.map((nbId) => ({
|
|
3659
|
-
id: makeNotebookLinkId(nbId, "note", note.id),
|
|
3660
|
-
notebookId: nbId,
|
|
3661
|
-
targetKind: "note",
|
|
3662
|
-
targetId: note.id,
|
|
3663
|
-
noteId: note.id,
|
|
3664
|
-
createdAt: now
|
|
3665
|
-
}));
|
|
3666
|
-
const promotedSessionIds = [];
|
|
3667
|
-
if (input.sessionIds && input.sessionIds.length > 0) {
|
|
3668
|
-
const wantedSessions = new Set(input.sessionIds);
|
|
3669
|
-
const sessions = await tx.readonly("sessions").getAllFromIndex("by-note", note.id);
|
|
3670
|
-
for (const sess of sessions) {
|
|
3671
|
-
if (!wantedSessions.has(sess.id)) continue;
|
|
3672
|
-
const sessNotebooks = dedupeNotebooks([
|
|
3673
|
-
"notebook/journal",
|
|
3674
|
-
...sess.notebookIds ?? [],
|
|
3675
|
-
...requestedTargets
|
|
3676
|
-
]);
|
|
3677
|
-
const updatedSess = {
|
|
3678
|
-
...sess,
|
|
3679
|
-
notebookIds: sessNotebooks,
|
|
3680
|
-
...input.shareSessionsPublicly !== void 0 ? { public: input.shareSessionsPublicly } : {}
|
|
3681
|
-
};
|
|
3682
|
-
await tx.readwrite("sessions").put(updatedSess);
|
|
3683
|
-
promotedSessionIds.push(sess.id);
|
|
3684
|
-
for (const nbId of sessNotebooks) {
|
|
3685
|
-
linkRows.push({
|
|
3686
|
-
id: makeNotebookLinkId(nbId, "session", sess.id),
|
|
3687
|
-
notebookId: nbId,
|
|
3688
|
-
targetKind: "session",
|
|
3689
|
-
targetId: sess.id,
|
|
3690
|
-
noteId: note.id,
|
|
3691
|
-
createdAt: now
|
|
3692
|
-
});
|
|
3693
|
-
}
|
|
3694
|
-
}
|
|
3695
|
-
}
|
|
3696
|
-
if (linkRows.length > 0) {
|
|
3697
|
-
await tx.readwrite("notebook_links").putMany(linkRows);
|
|
3698
|
-
}
|
|
3699
|
-
return {
|
|
3700
|
-
note: updatedNote,
|
|
3701
|
-
notebookIds: merged,
|
|
3702
|
-
promotedSessionIds
|
|
3703
|
-
};
|
|
3704
|
-
}
|
|
3705
|
-
);
|
|
3706
|
-
}
|
|
3707
|
-
async function setNoteNotebooks(storage, input) {
|
|
3708
|
-
const requested = dedupeNotebooks(input.notebookIds);
|
|
3709
|
-
const now = Date.now();
|
|
3710
|
-
return storage.transaction(["notes", "notebook_links", "block_revisions"], "readwrite", async (tx) => {
|
|
3711
|
-
const note = await tx.readonly("notes").get(input.noteId);
|
|
3712
|
-
if (!note) throw new Error(`Note not found: ${input.noteId}`);
|
|
3713
|
-
if (note.seedOrigin === "seed" || note.feedOrigin === "feed") {
|
|
3714
|
-
throw new Error(`Read-only Feed Note '${input.noteId}' cannot change Notebook membership.`);
|
|
3715
|
-
}
|
|
3716
|
-
const userTargets = requested.filter(
|
|
3717
|
-
(id) => id !== "notebook/journal" && id !== "notebook/playground"
|
|
3718
|
-
);
|
|
3719
|
-
for (const target of userTargets) {
|
|
3720
|
-
await assertWritableTargetNotebook(tx, target);
|
|
3721
|
-
await ensureUserNotebookLanding(tx, target, now);
|
|
3722
|
-
}
|
|
3723
|
-
const finalMemberships = dedupeNotebooks([
|
|
3724
|
-
...baseUserMemberships(note),
|
|
3725
|
-
...userTargets
|
|
3726
|
-
]);
|
|
3727
|
-
const existingLinks = await tx.readonly("notebook_links").getAllFromIndex("by-note", note.id);
|
|
3728
|
-
const linkStore = tx.readwrite("notebook_links");
|
|
3729
|
-
for (const link of existingLinks) {
|
|
3730
|
-
if (link.targetKind === "note" && link.targetId === note.id) {
|
|
3731
|
-
if (!finalMemberships.includes(toNotebookId$1(link.notebookId))) {
|
|
3732
|
-
await linkStore.delete(link.id);
|
|
3733
|
-
}
|
|
3734
|
-
}
|
|
3735
|
-
}
|
|
3736
|
-
for (const nbId of finalMemberships) {
|
|
3737
|
-
await linkStore.put({
|
|
3738
|
-
id: makeNotebookLinkId(nbId, "note", note.id),
|
|
3739
|
-
notebookId: nbId,
|
|
3740
|
-
targetKind: "note",
|
|
3741
|
-
targetId: note.id,
|
|
3742
|
-
noteId: note.id,
|
|
3743
|
-
createdAt: now
|
|
3744
|
-
});
|
|
3745
|
-
}
|
|
3746
|
-
const primaryUserNb = finalMemberships.find(
|
|
3747
|
-
(id) => id !== "notebook/journal" && id !== "notebook/playground"
|
|
3748
|
-
);
|
|
3749
|
-
const { notebookId: _priorSingle, ...rest } = note;
|
|
3750
|
-
const updatedNote = {
|
|
3751
|
-
...rest,
|
|
3752
|
-
notebookIds: finalMemberships,
|
|
3753
|
-
...primaryUserNb ? { notebookId: primaryUserNb } : {}
|
|
3754
|
-
};
|
|
3755
|
-
await tx.readwrite("notes").put(updatedNote);
|
|
3756
|
-
return finalMemberships;
|
|
3757
|
-
});
|
|
3758
|
-
}
|
|
3759
|
-
async function removeNoteFromNotebook(storage, noteId, notebookIdOrSlug) {
|
|
3760
|
-
const target = toNotebookId$1(notebookIdOrSlug);
|
|
3761
|
-
if (target === "notebook/journal") {
|
|
3762
|
-
throw new Error("Notes cannot be removed from private notebook/journal.");
|
|
3763
|
-
}
|
|
3764
|
-
const current = await getNoteNotebooks(storage, noteId);
|
|
3765
|
-
const remaining = current.filter((id) => id !== target);
|
|
3766
|
-
return setNoteNotebooks(storage, { noteId, notebookIds: remaining });
|
|
3767
|
-
}
|
|
3768
|
-
async function getNoteNotebooks(storage, noteId) {
|
|
3769
|
-
const note = await storage.readonly("notes").get(noteId);
|
|
3770
|
-
if (!note) return [];
|
|
3771
|
-
let linkNotebookIds = [];
|
|
3772
|
-
try {
|
|
3773
|
-
const links = await storage.readonly("notebook_links").getAllFromIndex("by-note", noteId);
|
|
3774
|
-
linkNotebookIds = links.filter((l) => l.targetKind === "note" && l.targetId === noteId).map((l) => l.notebookId);
|
|
3775
|
-
} catch {
|
|
3776
|
-
}
|
|
3777
|
-
return dedupeNotebooks([
|
|
3778
|
-
...baseUserMemberships(note),
|
|
3779
|
-
...note.notebookIds ?? [],
|
|
3780
|
-
...linkNotebookIds,
|
|
3781
|
-
...notebooksOfItem(note)
|
|
3782
|
-
]);
|
|
3783
|
-
}
|
|
3784
|
-
|
|
3785
|
-
// src/feed/ingestor.ts
|
|
3786
|
-
function mintUuidV4() {
|
|
3787
|
-
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
|
|
3788
|
-
return crypto.randomUUID();
|
|
3789
|
-
}
|
|
3790
|
-
const bytes = new Uint8Array(16);
|
|
3791
|
-
crypto.getRandomValues(bytes);
|
|
3792
|
-
bytes[6] = bytes[6] & 15 | 64;
|
|
3793
|
-
bytes[8] = bytes[8] & 63 | 128;
|
|
3794
|
-
const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
3795
|
-
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
3796
|
-
}
|
|
3797
|
-
async function getNotePublicationSummary(storage, noteId) {
|
|
3798
|
-
const note = await storage.readonly("notes").get(noteId);
|
|
3799
|
-
if (!note) {
|
|
3800
|
-
return derivePublicationVisibility({ notebookPublic: false, publicSessions: 0, totalSessions: 0 });
|
|
3801
|
-
}
|
|
3802
|
-
if (isPublishableNotebookLanding(note)) {
|
|
3803
|
-
const notebookPublic2 = note.public === true;
|
|
3804
|
-
const [allNotes, allSessions] = await Promise.all([
|
|
3805
|
-
storage.readonly("notes").getAll(),
|
|
3806
|
-
storage.readonly("sessions").getAll()
|
|
3807
|
-
]);
|
|
3808
|
-
let linkedNoteIds = /* @__PURE__ */ new Set();
|
|
3809
|
-
try {
|
|
3810
|
-
const links = await storage.readonly("notebook_links").getAllFromIndex("by-notebook", note.id);
|
|
3811
|
-
linkedNoteIds = new Set(links.filter((l) => l.targetKind === "note").map((l) => l.noteId));
|
|
3812
|
-
} catch {
|
|
3813
|
-
}
|
|
3814
|
-
const memberIds = new Set(
|
|
3815
|
-
allNotes.filter((n) => !isPublishableNotebookLanding(n) && (linkedNoteIds.has(n.id) || notebooksOfItem(n).includes(toNotebookId$1(note.id)))).map((n) => n.id)
|
|
3816
|
-
);
|
|
3817
|
-
const nbSessions = allSessions.filter((s) => memberIds.has(s.noteId));
|
|
3818
|
-
const pubCount = nbSessions.filter((s) => s.public === true).length;
|
|
3819
|
-
return derivePublicationVisibility({
|
|
3820
|
-
notebookPublic: notebookPublic2,
|
|
3821
|
-
publicSessions: pubCount,
|
|
3822
|
-
totalSessions: nbSessions.length,
|
|
3823
|
-
notebookId: note.id,
|
|
3824
|
-
notebookIds: [note.id],
|
|
3825
|
-
publicNotebookIds: notebookPublic2 ? [note.id] : []
|
|
3826
|
-
});
|
|
3827
|
-
}
|
|
3828
|
-
const linkedNotebooks = await getNoteNotebooks(storage, note.id);
|
|
3829
|
-
const candidateNotebooks = linkedNotebooks.length > 0 ? linkedNotebooks : note.notebookId ? [toNotebookId$1(note.notebookId)] : notebooksOfItem(note);
|
|
3830
|
-
const publicNotebookIds = [];
|
|
3831
|
-
for (const nbId of candidateNotebooks) {
|
|
3832
|
-
if (isNonPublishableNotebook(nbId)) continue;
|
|
3833
|
-
const landing = await storage.readonly("notes").get(nbId);
|
|
3834
|
-
if (landing && isPublishableNotebookLanding(landing) && landing.public === true) {
|
|
3835
|
-
publicNotebookIds.push(nbId);
|
|
3836
|
-
}
|
|
3837
|
-
}
|
|
3838
|
-
const notebookPublic = publicNotebookIds.length > 0;
|
|
3839
|
-
const primaryNbId = publicNotebookIds[0] ?? candidateNotebooks.find((id) => !isNonPublishableNotebook(id)) ?? candidateNotebooks[0] ?? notebookOfItem(note);
|
|
3840
|
-
let noteSessions;
|
|
3841
|
-
try {
|
|
3842
|
-
noteSessions = await storage.readonly("sessions").getAllFromIndex("by-note", noteId);
|
|
3843
|
-
} catch {
|
|
3844
|
-
noteSessions = (await storage.readonly("sessions").getAll()).filter((s) => s.noteId === noteId);
|
|
3845
|
-
}
|
|
3846
|
-
const publicSessions = noteSessions.filter((s) => s.public === true).length;
|
|
3847
|
-
return derivePublicationVisibility({
|
|
3848
|
-
notebookPublic,
|
|
3849
|
-
publicSessions,
|
|
3850
|
-
totalSessions: noteSessions.length,
|
|
3851
|
-
notebookId: primaryNbId,
|
|
3852
|
-
notebookIds: [...candidateNotebooks],
|
|
3853
|
-
publicNotebookIds
|
|
3854
|
-
});
|
|
3855
|
-
}
|
|
3856
|
-
async function setNotebookPublic(storage, notebookIdOrSlug, isPublic) {
|
|
3857
|
-
const notebookId = toNotebookId$1(notebookIdOrSlug);
|
|
3858
|
-
if (isNonPublishableNotebook(notebookId)) {
|
|
3859
|
-
throw new Error(`Notebook '${notebookId}' is private or system-managed and cannot be published.`);
|
|
3860
|
-
}
|
|
3861
|
-
return storage.transaction(["notes"], "readwrite", async (tx) => {
|
|
3862
|
-
const store = tx.readwrite("notes");
|
|
3863
|
-
const existing = await store.get(notebookId);
|
|
3864
|
-
if (existing && (existing.feedOrigin === "feed" || existing.seedOrigin === "seed")) {
|
|
3865
|
-
throw new Error(`Subscribed feed notebooks cannot be published directly (${notebookId}). Clone into a user notebook first.`);
|
|
3866
|
-
}
|
|
3867
|
-
const base = existing ?? {
|
|
3868
|
-
id: notebookId,
|
|
3869
|
-
title: notebookId.slice("notebook/".length),
|
|
3870
|
-
rawContent: `# ${notebookId.slice("notebook/".length)}
|
|
3871
|
-
`,
|
|
3872
|
-
sourceRevision: 1,
|
|
3873
|
-
blocks: {},
|
|
3874
|
-
createdAt: Date.now(),
|
|
3875
|
-
notebookId,
|
|
3876
|
-
seedOrigin: "user"
|
|
3877
|
-
};
|
|
3878
|
-
const updated = {
|
|
3879
|
-
...base,
|
|
3880
|
-
notebookId,
|
|
3881
|
-
public: isPublic
|
|
3882
|
-
};
|
|
3883
|
-
await store.put(updated);
|
|
3884
|
-
return updated;
|
|
3885
|
-
});
|
|
3886
|
-
}
|
|
3887
|
-
async function setSessionPublic(storage, sessionId, isPublic) {
|
|
3888
|
-
return storage.transaction(["sessions"], "readwrite", async (tx) => {
|
|
3889
|
-
const store = tx.readwrite("sessions");
|
|
3890
|
-
const existing = await store.get(sessionId);
|
|
3891
|
-
if (!existing) {
|
|
3892
|
-
throw new Error(`Session not found: ${sessionId}`);
|
|
3893
|
-
}
|
|
3894
|
-
const updated = { ...existing, public: isPublic };
|
|
3895
|
-
await store.put(updated);
|
|
3896
|
-
return updated;
|
|
3897
|
-
});
|
|
3898
|
-
}
|
|
3899
|
-
async function previewRemoteNotebook(reader, indexPath) {
|
|
3900
|
-
const raw = decodeUtf8(await reader.read(indexPath));
|
|
3901
|
-
return assertNotebookIndex(JSON.parse(raw));
|
|
3902
|
-
}
|
|
3903
|
-
async function previewRemoteRecord(reader, recordPath) {
|
|
3904
|
-
const raw = decodeUtf8(await reader.read(recordPath));
|
|
3905
|
-
return assertSeedRow(JSON.parse(raw));
|
|
3906
|
-
}
|
|
3907
|
-
async function cloneRemoteRecord(storage, reader, input) {
|
|
3908
|
-
const targetNotebookId = toNotebookId$1(input.targetNotebookId);
|
|
3909
|
-
const seedRow = await previewRemoteRecord(reader, input.record.recordPath);
|
|
3910
|
-
const newNoteId = mintUuidV4();
|
|
3911
|
-
const now = Date.now();
|
|
3912
|
-
const sourceRevision = 1;
|
|
3913
|
-
const blocks = {};
|
|
3914
|
-
const revisions = [];
|
|
3915
|
-
const blockIndex = [];
|
|
3916
|
-
for (const [key, block] of Object.entries(seedRow.blocks)) {
|
|
3917
|
-
blocks[key] = { ...block, version: 1, sourceRevision: 1 };
|
|
3918
|
-
revisions.push({
|
|
3919
|
-
noteId: newNoteId,
|
|
3920
|
-
blockId: block.id,
|
|
3921
|
-
version: 1,
|
|
3922
|
-
kind: block.kind,
|
|
3923
|
-
rawContent: seedRow.content.slice(block.from, block.to),
|
|
3924
|
-
savedAt: now,
|
|
3925
|
-
...block.dialect ? { dialect: block.dialect } : {},
|
|
3926
|
-
...block.sport ? { sport: block.sport } : {}
|
|
3927
|
-
});
|
|
3928
|
-
}
|
|
3929
|
-
for (const proj of seedRow.blockIndex) {
|
|
3930
|
-
blockIndex.push({
|
|
3931
|
-
...proj,
|
|
3932
|
-
id: `${newNoteId}:${proj.blockId}`,
|
|
3933
|
-
noteId: newNoteId,
|
|
3934
|
-
blockVersion: 1,
|
|
3935
|
-
sourceRevision: 1,
|
|
3936
|
-
isStatic: false,
|
|
3937
|
-
notebookId: targetNotebookId
|
|
3938
|
-
});
|
|
3939
|
-
}
|
|
3940
|
-
const blockEfforts = seedRow.blockEfforts.map((eff) => ({
|
|
3941
|
-
...eff,
|
|
3942
|
-
id: `${newNoteId}:${eff.blockId}:${eff.effortSlug}`,
|
|
3943
|
-
noteId: newNoteId,
|
|
3944
|
-
isStatic: false
|
|
3945
|
-
}));
|
|
3946
|
-
const blockEquipment = seedRow.blockEquipment.map((eq) => ({
|
|
3947
|
-
...eq,
|
|
3948
|
-
id: `${newNoteId}:${eq.blockId}:${eq.equipmentSlug}`,
|
|
3949
|
-
noteId: newNoteId,
|
|
3950
|
-
isStatic: false
|
|
3951
|
-
}));
|
|
3952
|
-
const clonedNote = {
|
|
3953
|
-
id: newNoteId,
|
|
3954
|
-
title: input.record.title || seedRow.blockIndex[0]?.noteTitle || "Cloned Note",
|
|
3955
|
-
rawContent: seedRow.content,
|
|
3956
|
-
sourceRevision,
|
|
3957
|
-
blocks,
|
|
3958
|
-
...input.record.date !== void 0 ? { date: input.record.date } : {},
|
|
3959
|
-
createdAt: now,
|
|
3960
|
-
notebookId: targetNotebookId,
|
|
3961
|
-
sourceId: `feed:${input.feedId}/${seedRow.path}`,
|
|
3962
|
-
sourcePath: seedRow.path,
|
|
3963
|
-
seedOrigin: "user"
|
|
3964
|
-
};
|
|
3965
|
-
const clonedSessions = [];
|
|
3966
|
-
const clonedEvents = [];
|
|
3967
|
-
if (input.includePublicTelemetry !== false && seedRow.telemetry) {
|
|
3968
|
-
const sessionIdMap = /* @__PURE__ */ new Map();
|
|
3969
|
-
for (const s of seedRow.telemetry.sessions) {
|
|
3970
|
-
const nextSid = mintUuidV4();
|
|
3971
|
-
sessionIdMap.set(s.id, nextSid);
|
|
3972
|
-
clonedSessions.push({
|
|
3973
|
-
...s,
|
|
3974
|
-
id: nextSid,
|
|
3975
|
-
noteId: newNoteId,
|
|
3976
|
-
public: false
|
|
3977
|
-
});
|
|
3978
|
-
}
|
|
3979
|
-
for (const ev of seedRow.telemetry.events) {
|
|
3980
|
-
const nextSid = sessionIdMap.get(ev.resultId);
|
|
3981
|
-
if (!nextSid) continue;
|
|
3982
|
-
clonedEvents.push({
|
|
3983
|
-
...ev,
|
|
3984
|
-
id: `${nextSid}:${ev.id}`,
|
|
3985
|
-
resultId: nextSid,
|
|
3986
|
-
noteId: newNoteId
|
|
3987
|
-
});
|
|
3988
|
-
}
|
|
3989
|
-
}
|
|
3990
|
-
await storage.transaction(
|
|
3991
|
-
["notes", "block_revisions", "block_index", "block_efforts", "block_equipment", "sessions", "events"],
|
|
3992
|
-
"readwrite",
|
|
3993
|
-
async (tx) => {
|
|
3994
|
-
const landing = await tx.readonly("notes").get(targetNotebookId);
|
|
3995
|
-
if (landing && (landing.feedOrigin === "feed" || landing.seedOrigin === "seed")) {
|
|
3996
|
-
throw new Error(`Target notebook '${targetNotebookId}' is read-only`);
|
|
3997
|
-
}
|
|
3998
|
-
await tx.readwrite("notes").put(clonedNote);
|
|
3999
|
-
if (revisions.length > 0) await tx.readwrite("block_revisions").putMany(revisions);
|
|
4000
|
-
if (blockIndex.length > 0) await tx.readwrite("block_index").putMany(blockIndex);
|
|
4001
|
-
if (blockEfforts.length > 0) await tx.readwrite("block_efforts").putMany(blockEfforts);
|
|
4002
|
-
if (blockEquipment.length > 0) await tx.readwrite("block_equipment").putMany(blockEquipment);
|
|
4003
|
-
if (clonedSessions.length > 0) await tx.readwrite("sessions").putMany(clonedSessions);
|
|
4004
|
-
if (clonedEvents.length > 0) await tx.readwrite("events").putMany(clonedEvents);
|
|
4005
|
-
}
|
|
4006
|
-
);
|
|
4007
|
-
return clonedNote;
|
|
4008
|
-
}
|
|
4009
|
-
async function exportPortableFilesFromStorage(storage, options = {}) {
|
|
4010
|
-
const telemetryFormat = options.telemetryFormat ?? "jsonl";
|
|
4011
|
-
const [allNotes, allSessions, allEvents, allRevisions] = await Promise.all([
|
|
4012
|
-
storage.readonly("notes").getAll(),
|
|
4013
|
-
storage.readonly("sessions").getAll(),
|
|
4014
|
-
storage.readonly("events").getAll(),
|
|
4015
|
-
storage.readonly("block_revisions").getAll()
|
|
4016
|
-
]);
|
|
4017
|
-
const wantedIds = options.noteIds ? new Set(options.noteIds) : null;
|
|
4018
|
-
const notes = allNotes.filter((n) => {
|
|
4019
|
-
if (wantedIds) return wantedIds.has(n.id);
|
|
4020
|
-
return n.seedOrigin !== "seed" && n.feedOrigin !== "feed";
|
|
4021
|
-
});
|
|
4022
|
-
const sessionsByNote = /* @__PURE__ */ new Map();
|
|
4023
|
-
for (const s of allSessions) {
|
|
4024
|
-
const arr = sessionsByNote.get(s.noteId) ?? [];
|
|
4025
|
-
arr.push(s);
|
|
4026
|
-
sessionsByNote.set(s.noteId, arr);
|
|
4027
|
-
}
|
|
4028
|
-
const eventsBySession = /* @__PURE__ */ new Map();
|
|
4029
|
-
for (const ev of allEvents) {
|
|
4030
|
-
const arr = eventsBySession.get(ev.resultId) ?? [];
|
|
4031
|
-
arr.push(ev);
|
|
4032
|
-
eventsBySession.set(ev.resultId, arr);
|
|
4033
|
-
}
|
|
4034
|
-
const revisionsByNote = /* @__PURE__ */ new Map();
|
|
4035
|
-
for (const rev of allRevisions) {
|
|
4036
|
-
const arr = revisionsByNote.get(rev.noteId) ?? [];
|
|
4037
|
-
arr.push(rev);
|
|
4038
|
-
revisionsByNote.set(rev.noteId, arr);
|
|
4039
|
-
}
|
|
4040
|
-
const files = [];
|
|
4041
|
-
const usedPaths = /* @__PURE__ */ new Set();
|
|
4042
|
-
for (const note of notes) {
|
|
4043
|
-
const baseStem = note.id.replace(/[^a-zA-Z0-9-_]/g, "_");
|
|
4044
|
-
let stem = baseStem;
|
|
4045
|
-
let i = 2;
|
|
4046
|
-
while (usedPaths.has(stem)) stem = `${baseStem}_${i++}`;
|
|
4047
|
-
usedPaths.add(stem);
|
|
4048
|
-
files.push({
|
|
4049
|
-
path: `${stem}.md`,
|
|
4050
|
-
content: composeNoteMarkdown(note)
|
|
4051
|
-
});
|
|
4052
|
-
const sessions = sessionsByNote.get(note.id) ?? [];
|
|
4053
|
-
const revisions = revisionsByNote.get(note.id) ?? [];
|
|
4054
|
-
const events = sessions.flatMap((s) => eventsBySession.get(s.id) ?? []);
|
|
4055
|
-
if (sessions.length > 0 || revisions.length > 0) {
|
|
4056
|
-
const bundle = {
|
|
4057
|
-
revisions,
|
|
4058
|
-
sessions,
|
|
4059
|
-
events
|
|
4060
|
-
};
|
|
4061
|
-
if (telemetryFormat === "jsonl" || telemetryFormat === "both") {
|
|
4062
|
-
files.push({
|
|
4063
|
-
path: `${stem}.jsonl`,
|
|
4064
|
-
content: serializeNoteBundleToJsonl(bundle) + "\n"
|
|
4065
|
-
});
|
|
4066
|
-
}
|
|
4067
|
-
if (telemetryFormat === "csv" || telemetryFormat === "both") {
|
|
4068
|
-
files.push({
|
|
4069
|
-
path: `${stem}.csv`,
|
|
4070
|
-
content: telemetryBundleToCsv(bundle)
|
|
4071
|
-
});
|
|
4072
|
-
}
|
|
4073
|
-
}
|
|
4074
|
-
}
|
|
4075
|
-
return files;
|
|
4076
|
-
}
|
|
4077
|
-
async function ingestPortableFilesIntoStorage(storage, files, options = {}) {
|
|
4078
|
-
const now = options.now ?? Date.now();
|
|
4079
|
-
const errors = [];
|
|
4080
|
-
let notesImported = 0;
|
|
4081
|
-
let revisionsImported = 0;
|
|
4082
|
-
let sessionsImported = 0;
|
|
4083
|
-
let eventsImported = 0;
|
|
4084
|
-
const mdFiles = files.filter((f) => /\.md$/i.test(f.path) && !/(?:^|\/)README\.md$/i.test(f.path));
|
|
4085
|
-
const jsonlFiles = files.filter((f) => /\.jsonl$/i.test(f.path));
|
|
4086
|
-
const jsonlStems = new Set(jsonlFiles.map((f) => f.path.replace(/\.jsonl$/i, "")));
|
|
4087
|
-
const csvFiles = files.filter(
|
|
4088
|
-
(f) => /\.csv$/i.test(f.path) && !jsonlStems.has(f.path.replace(/\.csv$/i, ""))
|
|
4089
|
-
);
|
|
4090
|
-
const telemetryBundles = [];
|
|
4091
|
-
for (const jf of jsonlFiles) {
|
|
4092
|
-
const parsed = parseNoteBundleFromJsonl(jf.content);
|
|
4093
|
-
errors.push(...parsed.errors.map((e) => `${jf.path}: ${e}`));
|
|
4094
|
-
telemetryBundles.push(...parsed.bundles);
|
|
4095
|
-
}
|
|
4096
|
-
for (const cf of csvFiles) {
|
|
4097
|
-
const parsed = csvToTelemetryBundle(cf.content);
|
|
4098
|
-
errors.push(...parsed.errors.map((e) => `${cf.path}: ${e}`));
|
|
4099
|
-
telemetryBundles.push(...parsed.bundles);
|
|
4100
|
-
}
|
|
4101
|
-
await storage.transaction(
|
|
4102
|
-
["notes", "block_revisions", "block_index", "tags", "note_tags", "sessions", "events"],
|
|
4103
|
-
"readwrite",
|
|
4104
|
-
async (tx) => {
|
|
4105
|
-
const noteStore = tx.readwrite("notes");
|
|
4106
|
-
const revStore = tx.readwrite("block_revisions");
|
|
4107
|
-
const idxStore = tx.readwrite("block_index");
|
|
4108
|
-
const tagStore = tx.readwrite("tags");
|
|
4109
|
-
const noteTagStore = tx.readwrite("note_tags");
|
|
4110
|
-
const sessionStore = tx.readwrite("sessions");
|
|
4111
|
-
const eventStore = tx.readwrite("events");
|
|
4112
|
-
for (const bundle of telemetryBundles) {
|
|
4113
|
-
if (bundle.revisions && bundle.revisions.length > 0) {
|
|
4114
|
-
await revStore.putMany(bundle.revisions);
|
|
4115
|
-
revisionsImported += bundle.revisions.length;
|
|
4116
|
-
}
|
|
4117
|
-
}
|
|
4118
|
-
for (const mf of mdFiles) {
|
|
4119
|
-
try {
|
|
4120
|
-
const fallbackTitle = (mf.path.split("/").at(-1) ?? "Imported Note").replace(/\.md$/i, "");
|
|
4121
|
-
const parsed = parseNoteMarkdown(mf.content, { fallbackTitle });
|
|
4122
|
-
const noteId = parsed.id ?? await seedNoteId(`import:${mf.path}:${now}`);
|
|
4123
|
-
const existing = await noteStore.get(noteId);
|
|
4124
|
-
const nextRev = existing && existing.rawContent !== parsed.rawContent ? existing.sourceRevision + 1 : existing?.sourceRevision ?? 1;
|
|
4125
|
-
const blocks = existing && existing.rawContent === parsed.rawContent ? existing.blocks : reconcileNoteBlocks(parsed.rawContent, {
|
|
4126
|
-
sourceRevision: nextRev,
|
|
4127
|
-
blocks: existing?.blocks,
|
|
4128
|
-
registeredWidgets: KNOWN_SECTION_WIDGETS
|
|
4129
|
-
});
|
|
4130
|
-
const noteRow = {
|
|
4131
|
-
...existing ?? {},
|
|
4132
|
-
id: noteId,
|
|
4133
|
-
title: parsed.title,
|
|
4134
|
-
rawContent: parsed.rawContent,
|
|
4135
|
-
sourceRevision: nextRev,
|
|
4136
|
-
blocks,
|
|
4137
|
-
...parsed.date !== void 0 ? { date: parsed.date } : {},
|
|
4138
|
-
createdAt: existing?.createdAt ?? parsed.date ?? now,
|
|
4139
|
-
...parsed.notebookId ? { notebookId: parsed.notebookId } : options.defaultNotebookId ? { notebookId: toNotebookId$1(options.defaultNotebookId) } : {},
|
|
4140
|
-
...parsed.public !== void 0 ? { public: parsed.public } : {},
|
|
4141
|
-
tags: parsed.tags,
|
|
4142
|
-
seedOrigin: "user"
|
|
4143
|
-
};
|
|
4144
|
-
await noteStore.put(noteRow);
|
|
4145
|
-
const sections = parseDocumentSections(noteRow.rawContent, { registeredWidgets: KNOWN_SECTION_WIDGETS });
|
|
4146
|
-
for (const [pos, b] of Object.values(blocks).entries()) {
|
|
4147
|
-
const existingRev = await revStore.get([noteId, b.id, b.version]);
|
|
4148
|
-
if (!existingRev) {
|
|
4149
|
-
await revStore.put({
|
|
4150
|
-
noteId,
|
|
4151
|
-
blockId: b.id,
|
|
4152
|
-
version: b.version,
|
|
4153
|
-
kind: b.kind,
|
|
4154
|
-
rawContent: noteRow.rawContent.slice(b.from, b.to),
|
|
4155
|
-
savedAt: now,
|
|
4156
|
-
...b.dialect ? { dialect: b.dialect } : {},
|
|
4157
|
-
...b.sport ? { sport: b.sport } : {}
|
|
4158
|
-
});
|
|
4159
|
-
}
|
|
4160
|
-
const sec = sections.find((s) => s.from === b.from && s.to === b.to);
|
|
4161
|
-
await idxStore.put({
|
|
4162
|
-
id: `${noteId}:${b.id}`,
|
|
4163
|
-
noteId,
|
|
4164
|
-
blockId: b.id,
|
|
4165
|
-
blockVersion: b.version,
|
|
4166
|
-
sourceRevision: nextRev,
|
|
4167
|
-
from: b.from,
|
|
4168
|
-
to: b.to,
|
|
4169
|
-
position: pos,
|
|
4170
|
-
dataType: b.kind,
|
|
4171
|
-
...b.kind === "wod" ? { blockContentId: blockContentId(sec?.scriptBlock?.content ?? noteRow.rawContent.slice(b.from, b.to)) } : {},
|
|
4172
|
-
rawContent: noteRow.rawContent.slice(b.from, b.to),
|
|
4173
|
-
noteTitle: noteRow.title,
|
|
4174
|
-
createdAt: noteRow.date ?? noteRow.createdAt,
|
|
4175
|
-
isStatic: false,
|
|
4176
|
-
...noteRow.notebookId ? { notebookId: noteRow.notebookId } : {}
|
|
4177
|
-
});
|
|
4178
|
-
}
|
|
4179
|
-
if (parsed.typedTags.length > 0) {
|
|
4180
|
-
const allTags = await tagStore.getAll();
|
|
4181
|
-
for (const item of parsed.typedTags) {
|
|
4182
|
-
const tagType = item.type ?? "general";
|
|
4183
|
-
let tag = allTags.find((t) => t.label === item.label && (t.type ?? "general") === tagType);
|
|
4184
|
-
if (!tag) {
|
|
4185
|
-
tag = { id: mintUuidV4(), label: item.label, type: tagType, createdAt: now };
|
|
4186
|
-
await tagStore.put(tag);
|
|
4187
|
-
allTags.push(tag);
|
|
4188
|
-
}
|
|
4189
|
-
const linkId = `${noteId}:${tag.id}`;
|
|
4190
|
-
await noteTagStore.put({ id: linkId, noteId, tagId: tag.id });
|
|
4191
|
-
}
|
|
4192
|
-
}
|
|
4193
|
-
notesImported++;
|
|
4194
|
-
} catch (err) {
|
|
4195
|
-
errors.push(`${mf.path}: ${err instanceof Error ? err.message : String(err)}`);
|
|
4196
|
-
}
|
|
4197
|
-
}
|
|
4198
|
-
for (const bundle of telemetryBundles) {
|
|
4199
|
-
if (bundle.note) {
|
|
4200
|
-
const existing = await noteStore.get(bundle.note.id);
|
|
4201
|
-
if (!existing) {
|
|
4202
|
-
const blocks = bundle.note.blocks ?? reconcileNoteBlocks(bundle.note.rawContent, {
|
|
4203
|
-
sourceRevision: bundle.note.sourceRevision ?? 1,
|
|
4204
|
-
registeredWidgets: KNOWN_SECTION_WIDGETS
|
|
4205
|
-
});
|
|
4206
|
-
await noteStore.put({
|
|
4207
|
-
id: bundle.note.id,
|
|
4208
|
-
title: bundle.note.title,
|
|
4209
|
-
rawContent: bundle.note.rawContent,
|
|
4210
|
-
sourceRevision: bundle.note.sourceRevision ?? 1,
|
|
4211
|
-
blocks,
|
|
4212
|
-
date: bundle.note.targetDate,
|
|
4213
|
-
createdAt: bundle.note.createdAt,
|
|
4214
|
-
tags: bundle.note.tags ?? [],
|
|
4215
|
-
...bundle.note.type ? { type: bundle.note.type } : {},
|
|
4216
|
-
...bundle.note.sourceId ? { sourceId: bundle.note.sourceId } : {},
|
|
4217
|
-
seedOrigin: "user"
|
|
4218
|
-
});
|
|
4219
|
-
for (const b of Object.values(blocks)) {
|
|
4220
|
-
const hasRev = await revStore.get([bundle.note.id, b.id, b.version]);
|
|
4221
|
-
if (!hasRev) {
|
|
4222
|
-
await revStore.put({
|
|
4223
|
-
noteId: bundle.note.id,
|
|
4224
|
-
blockId: b.id,
|
|
4225
|
-
version: b.version,
|
|
4226
|
-
kind: b.kind,
|
|
4227
|
-
rawContent: bundle.note.rawContent.slice(b.from, b.to),
|
|
4228
|
-
savedAt: now,
|
|
4229
|
-
...b.dialect ? { dialect: b.dialect } : {},
|
|
4230
|
-
...b.sport ? { sport: b.sport } : {}
|
|
4231
|
-
});
|
|
4232
|
-
}
|
|
4233
|
-
}
|
|
4234
|
-
notesImported++;
|
|
4235
|
-
}
|
|
4236
|
-
}
|
|
4237
|
-
for (const session of bundle.sessions) {
|
|
4238
|
-
try {
|
|
4239
|
-
const parent = await noteStore.get(session.noteId);
|
|
4240
|
-
if (!parent) {
|
|
4241
|
-
throw new Error(`Parent note ${session.noteId} does not exist`);
|
|
4242
|
-
}
|
|
4243
|
-
const rev = await revStore.get([session.noteId, session.blockId, session.blockVersion]);
|
|
4244
|
-
if (!rev || rev.kind !== "wod") {
|
|
4245
|
-
throw new Error(
|
|
4246
|
-
`Pinned wod BlockRevision [${session.noteId}, ${session.blockId}, ${session.blockVersion}] does not exist`
|
|
4247
|
-
);
|
|
4248
|
-
}
|
|
4249
|
-
const sessionEvents = bundle.events.filter((ev) => ev.resultId === session.id);
|
|
4250
|
-
for (const ev of sessionEvents) {
|
|
4251
|
-
if (ev.noteId !== session.noteId || ev.blockId !== session.blockId || ev.blockVersion !== session.blockVersion || ev.blockContentId !== session.blockContentId) {
|
|
4252
|
-
throw new Error(`Event ${ev.id} does not match session ${session.id} identity`);
|
|
4253
|
-
}
|
|
4254
|
-
}
|
|
4255
|
-
await sessionStore.put(session);
|
|
4256
|
-
if (sessionEvents.length > 0) {
|
|
4257
|
-
await eventStore.putMany(sessionEvents);
|
|
4258
|
-
eventsImported += sessionEvents.length;
|
|
4259
|
-
}
|
|
4260
|
-
sessionsImported++;
|
|
4261
|
-
} catch (err) {
|
|
4262
|
-
errors.push(
|
|
4263
|
-
`Failed to import session ${session.id}: ${err instanceof Error ? err.message : String(err)}`
|
|
4264
|
-
);
|
|
4265
|
-
}
|
|
4266
|
-
}
|
|
4267
|
-
}
|
|
4268
|
-
}
|
|
4269
|
-
);
|
|
4270
|
-
return {
|
|
4271
|
-
notesImported,
|
|
4272
|
-
revisionsImported,
|
|
4273
|
-
sessionsImported,
|
|
4274
|
-
eventsImported,
|
|
4275
|
-
errors
|
|
4276
|
-
};
|
|
4277
|
-
}
|
|
4278
|
-
function mintUuid() {
|
|
4279
|
-
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
|
|
4280
|
-
return crypto.randomUUID();
|
|
4281
|
-
}
|
|
4282
|
-
const bytes = new Uint8Array(16);
|
|
4283
|
-
crypto.getRandomValues(bytes);
|
|
4284
|
-
bytes[6] = bytes[6] & 15 | 64;
|
|
4285
|
-
bytes[8] = bytes[8] & 63 | 128;
|
|
4286
|
-
const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
4287
|
-
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
4288
|
-
}
|
|
4289
|
-
function utcCivilDateKey(epochMs) {
|
|
4290
|
-
const d = new Date(epochMs);
|
|
4291
|
-
const y = d.getFullYear();
|
|
4292
|
-
const m = String(d.getMonth() + 1).padStart(2, "0");
|
|
4293
|
-
const day = String(d.getDate()).padStart(2, "0");
|
|
4294
|
-
return `${y}-${m}-${day}`;
|
|
4295
|
-
}
|
|
4296
|
-
function computeWodContentId(blockSource) {
|
|
4297
|
-
const sec = parseDocumentSections(blockSource, { registeredWidgets: KNOWN_SECTION_WIDGETS }).find(
|
|
4298
|
-
(s) => s.scriptBlock
|
|
4299
|
-
);
|
|
4300
|
-
if (sec?.scriptBlock?.contentId) return sec.scriptBlock.contentId;
|
|
4301
|
-
if (sec?.scriptBlock?.content) return blockContentId(sec.scriptBlock.content);
|
|
4302
|
-
return void 0;
|
|
4303
|
-
}
|
|
4304
|
-
async function prepareJournalSessionRun(storage, input) {
|
|
4305
|
-
const startedAt = input.startedAt ?? Date.now();
|
|
4306
|
-
const sessionId = input.sessionId ?? mintUuid();
|
|
4307
|
-
const journalDate = input.journalDate ?? utcCivilDateKey(startedAt);
|
|
4308
|
-
return storage.transaction(
|
|
4309
|
-
["notes", "block_revisions", "block_index", "sessions", "page", "page_notes", "notebook_links"],
|
|
4310
|
-
"readwrite",
|
|
4311
|
-
async (tx) => {
|
|
4312
|
-
const sourceNote = await tx.readonly("notes").get(input.noteId);
|
|
4313
|
-
if (!sourceNote) {
|
|
4314
|
-
throw new Error(`Note not found: ${input.noteId}`);
|
|
4315
|
-
}
|
|
4316
|
-
const existingSession = await tx.readonly("sessions").get(sessionId);
|
|
4317
|
-
if (existingSession) {
|
|
4318
|
-
throw new Error(`Session already exists: ${sessionId}`);
|
|
4319
|
-
}
|
|
4320
|
-
const sourceBlocks = Object.values(sourceNote.blocks);
|
|
4321
|
-
const selectedSourceBlock = input.blockId ? sourceNote.blocks[input.blockId] ?? sourceBlocks.find((b) => b.id === input.blockId) : sourceBlocks.find((b) => b.kind === "wod");
|
|
4322
|
-
if (!selectedSourceBlock || selectedSourceBlock.kind !== "wod") {
|
|
4323
|
-
throw new Error(`Selected workout block is unavailable on Note '${input.noteId}'.`);
|
|
4324
|
-
}
|
|
4325
|
-
const nbOrigin = notebookOriginOfItem(sourceNote);
|
|
4326
|
-
const resolvedNb = notebookOfItem(sourceNote);
|
|
4327
|
-
const editable = isNoteEditable(sourceNote, nbOrigin, resolvedNb);
|
|
4328
|
-
if (!editable) {
|
|
4329
|
-
const clonedNoteId = mintUuid();
|
|
4330
|
-
let ordinal = 0;
|
|
4331
|
-
const clonedBlocks = reconcileNoteBlocks(sourceNote.rawContent, {
|
|
4332
|
-
sourceRevision: 1,
|
|
4333
|
-
registeredWidgets: KNOWN_SECTION_WIDGETS,
|
|
4334
|
-
createId: () => `blk-${clonedNoteId.slice(0, 8)}-${ordinal++}`
|
|
4335
|
-
});
|
|
4336
|
-
const clonedBlockList = Object.values(clonedBlocks);
|
|
4337
|
-
const mappedBlock = clonedBlockList.find(
|
|
4338
|
-
(b) => b.kind === "wod" && b.from === selectedSourceBlock.from && b.to === selectedSourceBlock.to
|
|
4339
|
-
) ?? clonedBlockList.find((b) => b.kind === "wod");
|
|
4340
|
-
if (!mappedBlock) {
|
|
4341
|
-
throw new Error("Cloned Journal Note contains no runnable workout block.");
|
|
4342
|
-
}
|
|
4343
|
-
const revisions = [];
|
|
4344
|
-
const projections = [];
|
|
4345
|
-
let pinnedRevision;
|
|
4346
|
-
for (const [pos, b] of clonedBlockList.entries()) {
|
|
4347
|
-
const slice = sourceNote.rawContent.slice(b.from, b.to);
|
|
4348
|
-
const rev = {
|
|
4349
|
-
noteId: clonedNoteId,
|
|
4350
|
-
blockId: b.id,
|
|
4351
|
-
version: 1,
|
|
4352
|
-
kind: b.kind,
|
|
4353
|
-
rawContent: slice,
|
|
4354
|
-
savedAt: startedAt,
|
|
4355
|
-
...b.dialect ? { dialect: b.dialect } : {},
|
|
4356
|
-
...b.sport ? { sport: b.sport } : {}
|
|
4357
|
-
};
|
|
4358
|
-
revisions.push(rev);
|
|
4359
|
-
if (b.id === mappedBlock.id) pinnedRevision = rev;
|
|
4360
|
-
const cid3 = b.kind === "wod" ? computeWodContentId(slice) : void 0;
|
|
4361
|
-
projections.push({
|
|
4362
|
-
id: `${clonedNoteId}:${b.id}`,
|
|
4363
|
-
noteId: clonedNoteId,
|
|
4364
|
-
blockId: b.id,
|
|
4365
|
-
blockVersion: 1,
|
|
4366
|
-
sourceRevision: 1,
|
|
4367
|
-
from: b.from,
|
|
4368
|
-
to: b.to,
|
|
4369
|
-
position: pos,
|
|
4370
|
-
dataType: b.kind,
|
|
4371
|
-
...cid3 ? { blockContentId: cid3 } : {},
|
|
4372
|
-
rawContent: slice,
|
|
4373
|
-
noteTitle: sourceNote.title,
|
|
4374
|
-
createdAt: startedAt,
|
|
4375
|
-
isStatic: false,
|
|
4376
|
-
notebookId: "notebook/journal"
|
|
4377
|
-
});
|
|
4378
|
-
}
|
|
4379
|
-
const provenance = buildNoteProvenance(sourceNote, resolvedNb, startedAt);
|
|
4380
|
-
const dateEpoch = Date.parse(`${journalDate}T12:00:00Z`);
|
|
4381
|
-
const clonedNote = {
|
|
4382
|
-
id: clonedNoteId,
|
|
4383
|
-
title: sourceNote.title,
|
|
4384
|
-
rawContent: sourceNote.rawContent,
|
|
4385
|
-
sourceRevision: 1,
|
|
4386
|
-
blocks: clonedBlocks,
|
|
4387
|
-
...Number.isFinite(dateEpoch) ? { date: dateEpoch } : {},
|
|
4388
|
-
createdAt: startedAt,
|
|
4389
|
-
type: "journal",
|
|
4390
|
-
sourceId: sourceNote.id,
|
|
4391
|
-
notebookIds: ["notebook/journal"],
|
|
4392
|
-
provenance,
|
|
4393
|
-
...sourceNote.tags?.length ? { tags: [...sourceNote.tags] } : {},
|
|
4394
|
-
seedOrigin: "user"
|
|
4395
|
-
};
|
|
4396
|
-
let existingPages;
|
|
4397
|
-
try {
|
|
4398
|
-
existingPages = await tx.readonly("page").getAllFromIndex("by-date", journalDate);
|
|
4399
|
-
} catch {
|
|
4400
|
-
existingPages = (await tx.readonly("page").getAll()).filter((p) => p.date === journalDate);
|
|
4401
|
-
}
|
|
4402
|
-
let targetPage = existingPages[0];
|
|
4403
|
-
if (!targetPage) {
|
|
4404
|
-
targetPage = {
|
|
4405
|
-
id: mintUuid(),
|
|
4406
|
-
date: journalDate,
|
|
4407
|
-
title: journalDate,
|
|
4408
|
-
createdAt: startedAt
|
|
4409
|
-
};
|
|
4410
|
-
await tx.readwrite("page").put(targetPage);
|
|
4411
|
-
}
|
|
4412
|
-
const pageNote = {
|
|
4413
|
-
id: mintUuid(),
|
|
4414
|
-
pageId: targetPage.id,
|
|
4415
|
-
noteId: clonedNoteId,
|
|
4416
|
-
createdAt: startedAt
|
|
4417
|
-
};
|
|
4418
|
-
const cid2 = computeWodContentId(pinnedRevision.rawContent);
|
|
4419
|
-
const session2 = {
|
|
4420
|
-
id: sessionId,
|
|
4421
|
-
noteId: clonedNoteId,
|
|
4422
|
-
blockId: mappedBlock.id,
|
|
4423
|
-
blockVersion: 1,
|
|
4424
|
-
...cid2 ? { blockContentId: cid2 } : {},
|
|
4425
|
-
origin: input.origin ?? "journal",
|
|
4426
|
-
pageId: targetPage.id,
|
|
4427
|
-
status: "in-progress",
|
|
4428
|
-
startTime: startedAt,
|
|
4429
|
-
endTime: startedAt,
|
|
4430
|
-
duration: 0,
|
|
4431
|
-
completed: false,
|
|
4432
|
-
createdAt: startedAt,
|
|
4433
|
-
notebookIds: ["notebook/journal"]
|
|
4434
|
-
};
|
|
4435
|
-
const links2 = [
|
|
4436
|
-
{
|
|
4437
|
-
id: makeNotebookLinkId("notebook/journal", "note", clonedNoteId),
|
|
4438
|
-
notebookId: "notebook/journal",
|
|
4439
|
-
targetKind: "note",
|
|
4440
|
-
targetId: clonedNoteId,
|
|
4441
|
-
noteId: clonedNoteId,
|
|
4442
|
-
createdAt: startedAt
|
|
4443
|
-
},
|
|
4444
|
-
{
|
|
4445
|
-
id: makeNotebookLinkId("notebook/journal", "session", sessionId),
|
|
4446
|
-
notebookId: "notebook/journal",
|
|
4447
|
-
targetKind: "session",
|
|
4448
|
-
targetId: sessionId,
|
|
4449
|
-
noteId: clonedNoteId,
|
|
4450
|
-
createdAt: startedAt
|
|
4451
|
-
}
|
|
4452
|
-
];
|
|
4453
|
-
await tx.readwrite("notes").put(clonedNote);
|
|
4454
|
-
if (revisions.length > 0) await tx.readwrite("block_revisions").putMany(revisions);
|
|
4455
|
-
if (projections.length > 0) await tx.readwrite("block_index").putMany(projections);
|
|
4456
|
-
await tx.readwrite("page_notes").put(pageNote);
|
|
4457
|
-
await tx.readwrite("sessions").put(session2);
|
|
4458
|
-
await tx.readwrite("notebook_links").putMany(links2);
|
|
4459
|
-
return {
|
|
4460
|
-
note: clonedNote,
|
|
4461
|
-
revision: pinnedRevision,
|
|
4462
|
-
session: session2,
|
|
4463
|
-
clonedFromReadOnly: true,
|
|
4464
|
-
upstreamNoteId: sourceNote.id
|
|
4465
|
-
};
|
|
4466
|
-
}
|
|
4467
|
-
const isPlayground = sourceNote.type === "playground" || sourceNote.sourceId === "playground" || sourceNote.notebookId === "notebook/playground";
|
|
4468
|
-
const baseNotebooks = isPlayground ? ["notebook/journal", "notebook/playground"] : ["notebook/journal"];
|
|
4469
|
-
const mergedNotebooks = [
|
|
4470
|
-
.../* @__PURE__ */ new Set([
|
|
4471
|
-
...baseNotebooks,
|
|
4472
|
-
...sourceNote.notebookIds ?? [],
|
|
4473
|
-
...sourceNote.notebookId ? [sourceNote.notebookId] : []
|
|
4474
|
-
])
|
|
4475
|
-
];
|
|
4476
|
-
const updatedNote = JSON.stringify(sourceNote.notebookIds) === JSON.stringify(mergedNotebooks) ? sourceNote : { ...sourceNote, notebookIds: mergedNotebooks };
|
|
4477
|
-
if (updatedNote !== sourceNote) {
|
|
4478
|
-
await tx.readwrite("notes").put(updatedNote);
|
|
4479
|
-
}
|
|
4480
|
-
let revision = await tx.readonly("block_revisions").get([sourceNote.id, selectedSourceBlock.id, selectedSourceBlock.version]);
|
|
4481
|
-
if (!revision) {
|
|
4482
|
-
revision = {
|
|
4483
|
-
noteId: sourceNote.id,
|
|
4484
|
-
blockId: selectedSourceBlock.id,
|
|
4485
|
-
version: selectedSourceBlock.version,
|
|
4486
|
-
kind: selectedSourceBlock.kind,
|
|
4487
|
-
rawContent: sourceNote.rawContent.slice(selectedSourceBlock.from, selectedSourceBlock.to),
|
|
4488
|
-
savedAt: startedAt,
|
|
4489
|
-
...selectedSourceBlock.dialect ? { dialect: selectedSourceBlock.dialect } : {},
|
|
4490
|
-
...selectedSourceBlock.sport ? { sport: selectedSourceBlock.sport } : {}
|
|
4491
|
-
};
|
|
4492
|
-
await tx.readwrite("block_revisions").put(revision);
|
|
4493
|
-
}
|
|
4494
|
-
const cid = computeWodContentId(revision.rawContent);
|
|
4495
|
-
const effectiveOrigin = input.origin ?? (isPlayground ? "playground" : "journal");
|
|
4496
|
-
const session = {
|
|
4497
|
-
id: sessionId,
|
|
4498
|
-
noteId: sourceNote.id,
|
|
4499
|
-
blockId: selectedSourceBlock.id,
|
|
4500
|
-
blockVersion: revision.version,
|
|
4501
|
-
...cid ? { blockContentId: cid } : {},
|
|
4502
|
-
origin: effectiveOrigin,
|
|
4503
|
-
status: "in-progress",
|
|
4504
|
-
startTime: startedAt,
|
|
4505
|
-
endTime: startedAt,
|
|
4506
|
-
duration: 0,
|
|
4507
|
-
completed: false,
|
|
4508
|
-
createdAt: startedAt,
|
|
4509
|
-
notebookIds: [...baseNotebooks]
|
|
4510
|
-
};
|
|
4511
|
-
const links = mergedNotebooks.map((nbId) => ({
|
|
4512
|
-
id: makeNotebookLinkId(nbId, "note", sourceNote.id),
|
|
4513
|
-
notebookId: nbId,
|
|
4514
|
-
targetKind: "note",
|
|
4515
|
-
targetId: sourceNote.id,
|
|
4516
|
-
noteId: sourceNote.id,
|
|
4517
|
-
createdAt: startedAt
|
|
4518
|
-
}));
|
|
4519
|
-
links.push({
|
|
4520
|
-
id: makeNotebookLinkId("notebook/journal", "session", sessionId),
|
|
4521
|
-
notebookId: "notebook/journal",
|
|
4522
|
-
targetKind: "session",
|
|
4523
|
-
targetId: sessionId,
|
|
4524
|
-
noteId: sourceNote.id,
|
|
4525
|
-
createdAt: startedAt
|
|
4526
|
-
});
|
|
4527
|
-
await tx.readwrite("sessions").put(session);
|
|
4528
|
-
await tx.readwrite("notebook_links").putMany(links);
|
|
4529
|
-
return {
|
|
4530
|
-
note: updatedNote,
|
|
4531
|
-
revision,
|
|
4532
|
-
session,
|
|
4533
|
-
clonedFromReadOnly: false
|
|
4534
|
-
};
|
|
4535
|
-
}
|
|
4536
|
-
);
|
|
4537
|
-
}
|
|
4538
|
-
async function resolveUpstreamProvenance(storage, note) {
|
|
4539
|
-
const sourceNoteId = note.provenance?.sourceNoteId ?? (note.sourceId && !note.sourceId.startsWith("/") && !note.sourceId.includes(":") && note.sourceId !== "playground" ? note.sourceId : void 0);
|
|
4540
|
-
if (!sourceNoteId) return null;
|
|
4541
|
-
const upstream = await storage.readonly("notes").get(sourceNoteId);
|
|
4542
|
-
if (upstream) {
|
|
4543
|
-
return {
|
|
4544
|
-
exists: true,
|
|
4545
|
-
sourceNoteId,
|
|
4546
|
-
title: upstream.title,
|
|
4547
|
-
sourceVersion: note.provenance?.sourceVersion,
|
|
4548
|
-
currentUpstreamVersion: upstream.seedVersion ?? upstream.sourceRevision,
|
|
4549
|
-
sourceCommit: note.provenance?.sourceCommit ?? upstream.seedCommit,
|
|
4550
|
-
feedSourceId: note.provenance?.feedSourceId ?? upstream.feedSourceId,
|
|
4551
|
-
sourceNotebookId: note.provenance?.sourceNotebookId ?? notebookOfItem(upstream),
|
|
4552
|
-
sourcePath: note.provenance?.sourcePath ?? upstream.sourcePath
|
|
4553
|
-
};
|
|
4554
|
-
}
|
|
4555
|
-
return {
|
|
4556
|
-
exists: false,
|
|
4557
|
-
sourceNoteId,
|
|
4558
|
-
sourceVersion: note.provenance?.sourceVersion,
|
|
4559
|
-
sourceCommit: note.provenance?.sourceCommit,
|
|
4560
|
-
feedSourceId: note.provenance?.feedSourceId,
|
|
4561
|
-
sourceNotebookId: note.provenance?.sourceNotebookId,
|
|
4562
|
-
sourcePath: note.provenance?.sourcePath
|
|
4563
|
-
};
|
|
4564
|
-
}
|
|
4565
|
-
function buildNoteProvenance(sourceNote, sourceNotebookId, clonedAt) {
|
|
4566
|
-
return {
|
|
4567
|
-
sourceNoteId: sourceNote.id,
|
|
4568
|
-
sourceVersion: sourceNote.seedVersion ?? sourceNote.sourceRevision,
|
|
4569
|
-
...sourceNote.seedCommit ? { sourceCommit: sourceNote.seedCommit } : {},
|
|
4570
|
-
...sourceNote.feedSourceId ? { feedSourceId: sourceNote.feedSourceId } : {},
|
|
4571
|
-
...sourceNotebookId ? { sourceNotebookId } : {},
|
|
4572
|
-
...sourceNote.sourcePath ? { sourcePath: sourceNote.sourcePath } : {},
|
|
4573
|
-
clonedAt
|
|
4574
|
-
};
|
|
4575
|
-
}
|
|
4576
87
|
|
|
4577
|
-
export {
|
|
88
|
+
export { defineLanguagePack, getRegisteredLanguagePacks, inMemoryEventStore, listLanguagePacks, registerLanguagePack, unregisterLanguagePack };
|
|
4578
89
|
//# sourceMappingURL=index.mjs.map
|
|
4579
90
|
//# sourceMappingURL=index.mjs.map
|