@vermeulen.solutions/eventual 0.0.0-stage → 0.18.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +139 -2
  3. package/astro/EventList.astro +57 -0
  4. package/astro/admin.d.mts +3 -0
  5. package/astro/admin.mjs +158 -0
  6. package/astro/blueprint.d.mts +51 -0
  7. package/astro/blueprint.mjs +236 -0
  8. package/astro/cache.ts +82 -0
  9. package/astro/descriptor.mjs +7 -0
  10. package/astro/editor-compat.mjs +197 -0
  11. package/astro/editor-i18n.d.mts +8 -0
  12. package/astro/editor-i18n.mjs +157 -0
  13. package/astro/event-details.ts +29 -0
  14. package/astro/event-list.ts +56 -0
  15. package/astro/feed.ts +201 -0
  16. package/astro/install.d.mts +9 -0
  17. package/astro/install.mjs +66 -0
  18. package/astro/schema.ts +88 -0
  19. package/dist/index.d.mts +5 -0
  20. package/dist/index.mjs +1585 -0
  21. package/dist/plugin.d.mts +6 -0
  22. package/dist/plugin.mjs +13 -0
  23. package/docs/collection-setup.md +46 -0
  24. package/docs/history.md +16 -0
  25. package/docs/native-modernization.md +99 -0
  26. package/docs/public-feed-caching.md +259 -0
  27. package/docs/registry-installation.md +13 -0
  28. package/docs/release-notes-0.14.0.md +27 -0
  29. package/docs/release-notes-0.14.1.md +40 -0
  30. package/docs/release-notes-0.15.0.md +18 -0
  31. package/docs/release-notes-0.16.0.md +7 -0
  32. package/docs/release-notes-0.17.0.md +7 -0
  33. package/docs/release-notes-0.18.0.md +8 -0
  34. package/docs/release-notes-0.18.1.md +7 -0
  35. package/docs/release-notes-0.18.2.md +6 -0
  36. package/docs/upgrade-0.13.0.md +21 -0
  37. package/docs/user-guide.md +40 -0
  38. package/emdash-plugin.jsonc +77 -0
  39. package/package.json +143 -4
  40. package/scripts/check-editor-installation.mjs +32 -0
  41. package/scripts/export-native-schema.mjs +28 -0
  42. package/scripts/upgrade-native-editor.mjs +296 -0
  43. package/src/domain/calendar-links.ts +80 -0
  44. package/src/domain/category.ts +32 -0
  45. package/src/domain/collections.ts +101 -0
  46. package/src/domain/date-time.ts +220 -0
  47. package/src/domain/description.ts +108 -0
  48. package/src/domain/event-data.ts +217 -0
  49. package/src/domain/event-expansion.ts +305 -0
  50. package/src/domain/event.ts +195 -0
  51. package/src/domain/icalendar.ts +165 -0
  52. package/src/domain/image.ts +18 -0
  53. package/src/domain/invocation-budget.ts +56 -0
  54. package/src/domain/messages.ts +8 -0
  55. package/src/domain/migration.ts +666 -0
  56. package/src/domain/native-calendar.ts +256 -0
  57. package/src/domain/native-references.ts +41 -0
  58. package/src/domain/native-source.ts +261 -0
  59. package/src/domain/native-validation.ts +366 -0
  60. package/src/domain/occurrences.ts +54 -0
  61. package/src/domain/portable-text.ts +180 -0
  62. package/src/domain/public-cache.ts +24 -0
  63. package/src/domain/recurrence-rule.ts +34 -0
  64. package/src/domain/recurrence.ts +350 -0
  65. package/src/domain/request-memo.ts +8 -0
  66. package/src/domain/schedule-history.ts +14 -0
  67. package/src/domain/text.ts +2 -0
  68. package/src/domain/time-entry.ts +23 -0
  69. package/src/domain/venue-adapter.ts +101 -0
  70. package/src/domain/venue.ts +42 -0
  71. package/src/public-event.ts +88 -0
  72. package/src/schema/blueprint.ts +315 -0
  73. package/src/storage.ts +257 -0
  74. package/transfer/index.d.mts +13 -0
  75. package/transfer/index.mjs +155 -0
package/package.json CHANGED
@@ -1,6 +1,145 @@
1
1
  {
2
2
  "name": "@vermeulen.solutions/eventual",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.18.2",
4
+ "license": "MIT",
5
+ "homepage": "https://eventual.rsvp/",
6
+ "type": "module",
7
+ "engines": {
8
+ "node": ">=24"
9
+ },
10
+ "packageManager": "npm@11.19.0",
11
+ "main": "dist/index.mjs",
12
+ "exports": {
13
+ ".": {
14
+ "import": "./dist/index.mjs",
15
+ "types": "./dist/index.d.mts"
16
+ },
17
+ "./sandbox": "./dist/plugin.mjs",
18
+ "./schema": {
19
+ "types": "./astro/blueprint.d.mts",
20
+ "import": "./astro/blueprint.mjs"
21
+ },
22
+ "./astro": "./astro/feed.ts",
23
+ "./astro/schema": "./astro/schema.ts",
24
+ "./astro/EventList.astro": "./astro/EventList.astro",
25
+ "./transfer": {
26
+ "types": "./transfer/index.d.mts",
27
+ "import": "./transfer/index.mjs"
28
+ },
29
+ "./admin": {
30
+ "types": "./astro/admin.d.mts",
31
+ "import": "./astro/admin.mjs"
32
+ },
33
+ "./admin/compat": "./astro/editor-compat.mjs",
34
+ "./admin/i18n": "./astro/editor-i18n.mjs",
35
+ "./install": {
36
+ "types": "./astro/install.d.mts",
37
+ "import": "./astro/install.mjs"
38
+ }
39
+ },
40
+ "files": [
41
+ "dist/*.mjs",
42
+ "dist/*.d.mts",
43
+ "emdash-plugin.jsonc",
44
+ "astro",
45
+ "transfer",
46
+ "src/domain",
47
+ "src/schema",
48
+ "src/storage.ts",
49
+ "src/public-event.ts",
50
+ "docs/native-modernization.md",
51
+ "docs/registry-installation.md",
52
+ "scripts/export-native-schema.mjs",
53
+ "scripts/upgrade-native-editor.mjs",
54
+ "scripts/check-editor-installation.mjs",
55
+ "docs/collection-setup.md",
56
+ "docs/upgrade-0.13.0.md",
57
+ "docs/user-guide.md",
58
+ "docs/history.md",
59
+ "docs/release-notes-0.14.0.md",
60
+ "docs/release-notes-0.14.1.md",
61
+ "docs/public-feed-caching.md",
62
+ "docs/release-notes-0.15.0.md",
63
+ "docs/release-notes-0.16.0.md",
64
+ "docs/release-notes-0.17.0.md",
65
+ "docs/release-notes-0.18.0.md",
66
+ "docs/release-notes-0.18.1.md",
67
+ "docs/release-notes-0.18.2.md"
68
+ ],
69
+ "scripts": {
70
+ "validate": "emdash-plugin validate",
71
+ "build": "npm run i18n:pack && emdash-plugin build && node scripts/build-host.mjs",
72
+ "prepack": "node scripts/build-host.mjs",
73
+ "dev": "emdash-plugin dev",
74
+ "typecheck": "tsc --noEmit",
75
+ "test": "emdash-plugin validate && vitest run",
76
+ "bundle": "emdash-plugin bundle",
77
+ "login": "emdash-plugin login",
78
+ "publish": "emdash-plugin publish",
79
+ "release:setup": "emdash-plugin release setup",
80
+ "budget": "node scripts/bundle-budget.mjs",
81
+ "registry:media": "node scripts/check-registry-media.mjs",
82
+ "test:tooling": "node --test scripts/*.test.mjs",
83
+ "test:package": "node scripts/verify-packed-astro.mjs",
84
+ "test:cache": "node scripts/verify-public-cache.mjs",
85
+ "test:editor": "node scripts/verify-editor-host.mjs",
86
+ "profile": "vitest run --config vitest.profile.config.ts",
87
+ "release:prepare": "node scripts/prepare-release.mjs",
88
+ "i18n:pack": "node node_modules/@vermeulen.solutions/eventual-locales/scripts/pack-manifest.mjs core src/ui/locales"
89
+ },
90
+ "peerDependencies": {
91
+ "@emdash-cms/admin": ">=1.2.0 <2.0.0",
92
+ "astro": ">=7.3.2 <8.0.0",
93
+ "emdash": ">=1.2.0 <2.0.0",
94
+ "kysely": "^0.29.0",
95
+ "react": "^19.0.0",
96
+ "vite": ">=8.3.0 <9.0.0"
97
+ },
98
+ "devDependencies": {
99
+ "@emdash-cms/admin": "1.4.0",
100
+ "@emdash-cms/plugin-cli": "0.13.5",
101
+ "@emdash-cms/plugin-test": "0.2.11",
102
+ "@playwright/test": "1.64.1",
103
+ "emdash": "1.4.0",
104
+ "ical.js": "^2.2.1",
105
+ "jsonc-parser": "3.3.1",
106
+ "sharp": "0.35.5",
107
+ "typescript": "^5.9.0",
108
+ "vitest": "^4.1.0"
109
+ },
110
+ "dependencies": {
111
+ "@emdash-cms/blocks": "1.4.0",
112
+ "@lingui/core": "5.9.5",
113
+ "zod": "4.5.4",
114
+ "@vermeulen.solutions/eventual-locales": "0.1.10"
115
+ },
116
+ "allowScripts": {
117
+ "esbuild": true,
118
+ "workerd": true
119
+ },
120
+ "peerDependenciesMeta": {
121
+ "astro": {
122
+ "optional": true
123
+ },
124
+ "vite": {
125
+ "optional": true
126
+ },
127
+ "@emdash-cms/admin": {
128
+ "optional": true
129
+ },
130
+ "react": {
131
+ "optional": true
132
+ },
133
+ "kysely": {
134
+ "optional": true
135
+ }
136
+ },
137
+ "overrides": {
138
+ "sharp": "0.35.5",
139
+ "undici@7.29.0": "7.29.1"
140
+ },
141
+ "description": "Native event collections for EmDash: Portable Text, localization, recurrence, saved venues and multilingual iCalendar feeds.",
142
+ "bin": {
143
+ "eventual-schema": "scripts/export-native-schema.mjs"
144
+ }
145
+ }
@@ -0,0 +1,32 @@
1
+ /** Read-only readiness check. Configuration is finally verified by astro build. */
2
+ import { createRequire } from "node:module";
3
+ import { readFileSync, existsSync } from "node:fs";
4
+ import { resolve } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { installedVersion, testedVersions, checkToolchainVersions } from "../astro/install.mjs";
7
+
8
+ export function checkInstallation(site) {
9
+ const root = resolve(site);
10
+ const resolver = createRequire(resolve(root, "package.json"));
11
+ const checks = [];
12
+ for (const [name, expected] of Object.entries(testedVersions)) {
13
+ try {
14
+ const actual = installedVersion(name, resolver);
15
+ checks.push({ name, expected, actual, ok: expected.includes(actual) });
16
+ } catch (error) { checks.push({ name, expected, ok: false, error: error.message }); }
17
+ }
18
+ try { checks.push({name:"editor-toolchain",actual:checkToolchainVersions(name=>installedVersion(name,resolver)),ok:true}); }
19
+ catch(error) { checks.push({name:"editor-toolchain",ok:false,error:error.message}); }
20
+ const configPath = ["astro.config.mjs", "astro.config.ts", "astro.config.js"].map(name => resolve(root, name)).find(existsSync);
21
+ const source = configPath ? readFileSync(configPath, "utf8") : "";
22
+ const candidate = /from\s*["']eventual\/install["']/.test(source) || (source.includes("eventualEditor(") && source.includes("eventualEditorCompatibility("));
23
+ checks.push({ name: "host-config-candidate", ok: candidate, path: configPath, requiresBuildVerification: true });
24
+ return { site: root, checks, prerequisitesReady: checks.every(check => check.ok), next: "Run astro check and astro build. For an existing native schema, stop writers and preview the documented database upgrade. A registry-only update does not install the frontend companion." };
25
+ }
26
+ if (process.argv[1] === fileURLToPath(import.meta.url)) {
27
+ const args = process.argv.slice(2);
28
+ if (args.length !== 2 || args[0] !== "--site") throw new Error("Usage: node scripts/check-editor-installation.mjs --site /absolute/site/path");
29
+ const report = checkInstallation(args[1]);
30
+ console.log(JSON.stringify(report, null, 2));
31
+ if (!report.prerequisitesReady) process.exitCode = 1;
32
+ }
@@ -0,0 +1,28 @@
1
+ #!/usr/bin/env node
2
+ /** Emit a schema-only seed. Never connect to a database or overwrite a file. */
3
+ import { writeFileSync } from 'node:fs';
4
+ import {createEventsCollectionBlueprint,createVenuesCollectionBlueprint,createOrganizersCollectionBlueprint} from '../astro/blueprint.mjs';
5
+ const args=process.argv.slice(2);
6
+ let eventCollection='events',venueCollection='venues',organizerCollection='organizers',locale='fr',output,reuseVenues=false,reuseOrganizers=false,legacyCompatibility=false;
7
+ for(let i=0;i<args.length;i++) {
8
+ if(args[i]==='--event-collection') eventCollection=args[++i];
9
+ else if(args[i]==='--venue-collection') venueCollection=args[++i];
10
+ else if(args[i]==='--organizer-collection') organizerCollection=args[++i];
11
+ else if(args[i]==='--locale') locale=args[++i];
12
+ else if(args[i]==='--reuse-venues') reuseVenues=true;
13
+ else if(args[i]==='--reuse-organizers') reuseOrganizers=true;
14
+ else if(args[i]==='--legacy-compatibility') legacyCompatibility=true;
15
+ else if(args[i]==='--output') output=args[++i];
16
+ else throw new Error('Use --event-collection, --venue-collection, --organizer-collection, --locale, --reuse-venues, --reuse-organizers, --legacy-compatibility and/or --output.');
17
+ }
18
+ for(const slug of [eventCollection,venueCollection,organizerCollection]) if(!slug || !/^[a-z][a-z0-9_]{0,62}$/.test(slug)) throw new Error('Invalid collection slug.');
19
+ if(new Set([eventCollection,venueCollection,organizerCollection]).size!==3) throw new Error('Use separate event, venue and organizer collections.');
20
+ if(!locale || Intl.getCanonicalLocales(locale)[0]!==locale) throw new Error('Use a canonical locale such as fr or en.');
21
+ const events=createEventsCollectionBlueprint({eventCollection,venueCollection,organizerCollection,bindRelations:false,legacyCompatibility});
22
+ // Stock core widgets only: the sandbox panel supplies schedule controls.
23
+ const collections=[events];
24
+ if(!reuseVenues) collections.push({...createVenuesCollectionBlueprint({legacyCompatibility}),slug:venueCollection});
25
+ if(!reuseOrganizers) collections.push({...createOrganizersCollectionBlueprint({legacyCompatibility}),slug:organizerCollection});
26
+ for(const collection of collections) for(const field of collection.fields) {delete field.widget;if(field.options) delete field.options.eventualEditor;}
27
+ const json=JSON.stringify({version:'1',defaultLocale:locale,collections},null,2)+'\n';
28
+ if(output) writeFileSync(output,json,{encoding:'utf8',flag:'wx'}); else process.stdout.write(json);
@@ -0,0 +1,296 @@
1
+ /**
2
+ * Versioned, offline SQLite upgrade for EmDash 1.0.1. Default: rollback preview.
3
+ * Stop the site's writers, then --apply --backup <new absolute backup path>.
4
+ * Uses SchemaRegistry for schema mutations; backfills only added reference columns.
5
+ */
6
+ import { DatabaseSync, backup } from "node:sqlite";
7
+ import { existsSync, readFileSync } from "node:fs";
8
+ import { resolve, dirname } from "node:path";
9
+ import { fileURLToPath } from "node:url";
10
+ import { createRequire } from "node:module";
11
+ import { Kysely } from "kysely";
12
+ import { createDialect } from "emdash/db/sqlite";
13
+ import { SchemaRegistry } from "emdash";
14
+ import {
15
+ createEventsCollectionBlueprint,
16
+ createVenuesCollectionBlueprint,
17
+ createOrganizersCollectionBlueprint,
18
+ } from "../astro/blueprint.mjs";
19
+
20
+ export async function upgradeNativeEditor(db, { apply = false } = {}) {
21
+ const report = {
22
+ applied: apply,
23
+ fields: [],
24
+ entries: 0,
25
+ revisions: 0,
26
+ warnings: [],
27
+ };
28
+ const previewRollback = new Error("preview rollback");
29
+ try {
30
+ await db.transaction().execute(async (trx) => {
31
+ const registry = new SchemaRegistry(trx);
32
+ const schema = await registry.getCollectionWithFields("events");
33
+ if (!schema?.fields.some((field) => field.slug === "recurrence"))
34
+ throw new Error("Not an Eventual events schema.");
35
+ const organizerField = schema.fields.find(
36
+ (field) => field.slug === "organizer_ref",
37
+ );
38
+ const organizerTarget =
39
+ organizerField?.validation?.targetCollection ??
40
+ organizerField?.options?.collection ??
41
+ "organizers";
42
+ if (
43
+ organizerTarget === "organizers" &&
44
+ !(await registry.getCollection("organizers"))
45
+ ) {
46
+ const { fields, ...collection } = createOrganizersCollectionBlueprint();
47
+ await registry.createCollection(collection);
48
+ for (const field of fields) {
49
+ const { description, ...input } = field;
50
+ await registry.createField("organizers", input);
51
+ }
52
+ report.fields.push("organizers (created)");
53
+ }
54
+ if (!organizerField) {
55
+ await registry.createField("events", {
56
+ slug: "organizer_ref",
57
+ label: "Saved organizer",
58
+ type: "reference",
59
+ translatable: false,
60
+ options: { collection: organizerTarget },
61
+ widget: "eventual-editor:managed",
62
+ });
63
+ report.fields.push("events.organizer_ref (added)");
64
+ }
65
+ const bindings = [];
66
+ for (const [original, alias, fallback] of [
67
+ ["venue", "venue_id", "venues"],
68
+ ["organizer_ref", "organizer_id", "organizers"],
69
+ ]) {
70
+ const field = schema.fields.find((field) => field.slug === original);
71
+ if (!field) continue;
72
+ const target =
73
+ field.validation?.targetCollection ??
74
+ field.options?.collection ??
75
+ fallback;
76
+ if (!/^[a-z][a-z0-9_]*$/.test(target))
77
+ throw new Error("Invalid reference target.");
78
+ if (field.validation?.relation) {
79
+ if (
80
+ field.validation.relationSide !== "parent" ||
81
+ field.validation.multiple === true
82
+ )
83
+ throw new Error(
84
+ "Only single parent-side Eventual bindings are supported.",
85
+ );
86
+ const relation = await trx
87
+ .selectFrom("_emdash_relations")
88
+ .selectAll()
89
+ .where("slug", "=", field.validation.relation)
90
+ .executeTakeFirst();
91
+ if (
92
+ !relation ||
93
+ relation.parent_collection !== "events" ||
94
+ relation.child_collection !== target
95
+ )
96
+ throw new Error("Reference relation does not match schema.");
97
+ let existing = schema.fields.find((field) => field.slug === alias);
98
+ if (!existing) {
99
+ await registry.createField("events", {
100
+ slug: alias,
101
+ label: original === "venue" ? "Saved venue" : "Saved organizer",
102
+ type: "reference",
103
+ translatable: false,
104
+ options: { collection: target },
105
+ widget: "eventual-editor:managed",
106
+ });
107
+ report.fields.push("events." + alias + " (added)");
108
+ } else if (
109
+ existing.type !== "reference" ||
110
+ existing.validation?.relation ||
111
+ existing.options?.collection !== target ||
112
+ existing.translatable
113
+ )
114
+ throw new Error(
115
+ "Existing " + alias + " has an incompatible definition.",
116
+ );
117
+ bindings.push({ original, alias, target, relation });
118
+ }
119
+ }
120
+ for (const blueprint of [
121
+ createEventsCollectionBlueprint(),
122
+ createVenuesCollectionBlueprint(),
123
+ createOrganizersCollectionBlueprint(),
124
+ ]) {
125
+ const collection = await registry.getCollectionWithFields(
126
+ blueprint.slug,
127
+ );
128
+ if (!collection) continue;
129
+ for (const definition of blueprint.fields) {
130
+ const installed=collection.fields.find(field=>field.slug === definition.slug);
131
+ if(!installed) continue;
132
+ if(installed.label === definition.label && installed.options?.eventualEditor === true && (!definition.widget || installed.widget === definition.widget)) continue;
133
+ // Preserve type, required/default, target, flags and validation. Cosmetic upgrade only.
134
+ await registry.updateField(blueprint.slug, definition.slug, {
135
+ label: definition.label,
136
+ options: { ...installed.options, eventualEditor: true },
137
+ ...(definition.widget ? { widget: definition.widget } : {}),
138
+ });
139
+ report.fields.push(blueprint.slug + "." + definition.slug);
140
+ }
141
+ }
142
+ const rows = await trx.selectFrom("ec_events").selectAll().execute();
143
+ for (const binding of bindings) {
144
+ const targets = await trx
145
+ .selectFrom("ec_" + binding.target)
146
+ .select(["id", "locale", "translation_group", "status"])
147
+ .execute();
148
+ const edges = await trx
149
+ .selectFrom("_emdash_content_references")
150
+ .selectAll()
151
+ .where("relation_id", "=", binding.relation.id)
152
+ .orderBy("sort_order")
153
+ .execute();
154
+ const resolveGroup = (groups) => {
155
+ if (
156
+ !Array.isArray(groups) ||
157
+ groups.length > 1 ||
158
+ groups.some((group) => typeof group !== "string")
159
+ )
160
+ throw new Error("Invalid single-reference selection.");
161
+ if (!groups.length) return "";
162
+ const matches = targets
163
+ .filter((item) => item.translation_group === groups[0])
164
+ .sort((a, b) => a.id.localeCompare(b.id));
165
+ if (!matches.length)
166
+ throw new Error(
167
+ "A reference points to a missing translation group. Repair it before upgrading.",
168
+ );
169
+ // Shared fields must use the same canonical entry ID across all event locales.
170
+ return (
171
+ matches.find((item) => item.status === "published") ?? matches[0]
172
+ ).id;
173
+ };
174
+ for (const row of rows) {
175
+ const groups = edges
176
+ .filter((edge) => edge.parent_group === row.translation_group)
177
+ .map((edge) => edge.child_group);
178
+ const live = resolveGroup(groups);
179
+ // Once populated, the canonical column is authoritative. Reruns never overwrite edits.
180
+ if (row[binding.alias] === null || row[binding.alias] === undefined) {
181
+ await trx
182
+ .updateTable("ec_events")
183
+ .set({ [binding.alias]: live })
184
+ .where("id", "=", row.id)
185
+ .execute();
186
+ report.entries++;
187
+ }
188
+ const revisions = await trx
189
+ .selectFrom("revisions")
190
+ .selectAll()
191
+ .where("collection", "=", "events")
192
+ .where("entry_id", "=", row.id)
193
+ .execute();
194
+ for (const revision of revisions) {
195
+ const data = JSON.parse(revision.data);
196
+ if (Object.hasOwn(data, binding.alias)) continue;
197
+ const staged = data._references;
198
+ let id;
199
+ if (staged && Object.hasOwn(staged, binding.original))
200
+ id = resolveGroup(staged[binding.original]);
201
+ else if (Object.hasOwn(data, binding.original)) {
202
+ const previous = data[binding.original];
203
+ if (previous === null || previous === "") id = "";
204
+ else if (
205
+ typeof previous === "string" &&
206
+ targets.some((target) => target.id === previous)
207
+ )
208
+ id = previous;
209
+ else
210
+ throw new Error(
211
+ "A historical reference cannot be resolved safely.",
212
+ );
213
+ } else if (
214
+ revision.id === row.live_revision_id ||
215
+ revision.id === row.draft_revision_id
216
+ )
217
+ id = live;
218
+ else {
219
+ report.warnings.push(
220
+ "Historical revision " +
221
+ revision.id +
222
+ " has no reference snapshot; left unchanged.",
223
+ );
224
+ continue;
225
+ }
226
+ data[binding.alias] = id;
227
+ await trx
228
+ .updateTable("revisions")
229
+ .set({ data: JSON.stringify(data) })
230
+ .where("id", "=", revision.id)
231
+ .execute();
232
+ report.revisions++;
233
+ }
234
+ }
235
+ }
236
+ if (!apply) throw previewRollback;
237
+ });
238
+ } catch (error) {
239
+ if (error !== previewRollback) throw error;
240
+ }
241
+ return report;
242
+ }
243
+
244
+ if (
245
+ process.argv[1] &&
246
+ resolve(process.argv[1]) === fileURLToPath(import.meta.url)
247
+ ) {
248
+ const args = process.argv.slice(2);
249
+ let database,
250
+ backupPath,
251
+ apply = false;
252
+ for (let i = 0; i < args.length; i++) {
253
+ if (args[i] === "--database") database = args[++i];
254
+ else if (args[i] === "--backup") backupPath = args[++i];
255
+ else if (args[i] === "--apply") apply = true;
256
+ else
257
+ throw new Error(
258
+ "Use --database <existing sqlite file> [--apply --backup <new file>].",
259
+ );
260
+ }
261
+ if (!database || !existsSync(database))
262
+ throw new Error("Specify an existing database file.");
263
+ database = resolve(database);
264
+ const coreEntry = createRequire(import.meta.url).resolve("emdash");
265
+ const coreVersion = JSON.parse(
266
+ readFileSync(resolve(dirname(coreEntry), "..", "package.json"), "utf8"),
267
+ ).version;
268
+ if (coreVersion !== "1.0.1")
269
+ throw new Error(
270
+ "This upgrade was verified on EmDash 1.0.1. Review before using another version.",
271
+ );
272
+ if (apply) {
273
+ if (
274
+ !backupPath ||
275
+ existsSync(backupPath) ||
276
+ resolve(backupPath) === database ||
277
+ !existsSync(dirname(resolve(backupPath)))
278
+ )
279
+ throw new Error(
280
+ "Apply requires a new backup path in an existing directory.",
281
+ );
282
+ const source = new DatabaseSync(database, { readOnly: true });
283
+ await backup(source, resolve(backupPath));
284
+ source.close();
285
+ }
286
+ const db = new Kysely({
287
+ dialect: createDialect({ url: "file:" + database }),
288
+ });
289
+ try {
290
+ console.log(
291
+ JSON.stringify(await upgradeNativeEditor(db, { apply }), null, 2),
292
+ );
293
+ } finally {
294
+ await db.destroy();
295
+ }
296
+ }
@@ -0,0 +1,80 @@
1
+ import { safeHttpUrl } from "./venue";
2
+ export interface CalendarLinks {
3
+ google: string;
4
+ outlook: string;
5
+ office365: string;
6
+ ics: string;
7
+ }
8
+
9
+ export interface CalendarEventInput {
10
+ id: string;
11
+ title: string;
12
+ description?: string;
13
+ start: string;
14
+ end: string;
15
+ allDay: boolean;
16
+ timezone?: string;
17
+ location?: string;
18
+ locationType?: "physical" | "virtual" | "hybrid";
19
+ virtualUrl?: string;
20
+ }
21
+
22
+
23
+ /**
24
+ * Builds standard 1-click web calendar links for Google Calendar, Outlook Web,
25
+ * Office 365, and Apple/desktop iCal (.ics) download.
26
+ */
27
+ export function buildCalendarLinks(event: CalendarEventInput, siteUrl = ""): CalendarLinks {
28
+ const title = event.title || "Event";
29
+ const onlineUrl = safeHttpUrl(event.virtualUrl ?? "");
30
+ const details = [event.description || "", onlineUrl].filter(Boolean).join("\n\n");
31
+
32
+ let loc = event.location || "";
33
+ if (event.locationType === "virtual") {
34
+ loc = onlineUrl || loc;
35
+ } else if (event.locationType === "hybrid" && onlineUrl && loc) {
36
+ loc = `${loc} · ${onlineUrl}`;
37
+ }
38
+
39
+ let googleDates: string;
40
+ let outlookStart: string;
41
+ let outlookEnd: string;
42
+ let isAllDayParam = "";
43
+
44
+ if (event.allDay) {
45
+ const startDate = event.start.slice(0, 10).replace(/-/g, "");
46
+ // In iCalendar/Google, the end date for all-day is exclusive (next day)
47
+ const endObj = new Date(event.end.slice(0, 10) + "T00:00:00Z");
48
+ endObj.setUTCDate(endObj.getUTCDate() + 1);
49
+ const endDate = endObj.toISOString().slice(0, 10).replace(/-/g, "");
50
+ googleDates = `${startDate}/${endDate}`;
51
+ outlookStart = event.start.slice(0, 10);
52
+ outlookEnd = endObj.toISOString().slice(0, 10);
53
+ isAllDayParam = "&allday=true";
54
+ } else {
55
+ const startUtc = new Date(event.start).toISOString();
56
+ const endUtc = new Date(event.end).toISOString();
57
+ const startCompact = startUtc.replace(/[-:]/g, "").replace(/\.\d{3}/, "");
58
+ const endCompact = endUtc.replace(/[-:]/g, "").replace(/\.\d{3}/, "");
59
+ googleDates = `${startCompact}/${endCompact}`;
60
+ outlookStart = startUtc;
61
+ outlookEnd = endUtc;
62
+ }
63
+
64
+ const enc = encodeURIComponent;
65
+ const google = `https://calendar.google.com/calendar/render?action=TEMPLATE&text=${enc(title)}&dates=${googleDates}&details=${enc(details)}&location=${enc(loc)}`;
66
+ const q = `path=/calendar/action/compose&rru=addevent&subject=${enc(title)}&body=${enc(details)}&location=${enc(loc)}&startdt=${enc(outlookStart)}&enddt=${enc(outlookEnd)}${isAllDayParam}`;
67
+ const outlook = `https://outlook.live.com/calendar/0/deeplink/compose?${q}`;
68
+ const office365 = `https://outlook.office.com/calendar/0/deeplink/compose?${q}`;
69
+
70
+ const eventBaseId = event.id.split("#")[0]!;
71
+ const icsPath = `/_emdash/api/plugins/eventual/calendar?eventId=${enc(eventBaseId)}`;
72
+ const ics = siteUrl ? new URL(icsPath, siteUrl).href : icsPath;
73
+
74
+ return {
75
+ google,
76
+ outlook,
77
+ office365,
78
+ ics,
79
+ };
80
+ }
@@ -0,0 +1,32 @@
1
+ import { reject } from './messages';
2
+ /** Normalize category labels while retaining the first label's display casing. */
3
+ export function normalizeCategories(values: string | string[]): string[] {
4
+ const labels = typeof values === "string" ? values.split(/[,\r\n]+/) : values;
5
+ const result: string[] = [];
6
+ const seen = new Set<string>();
7
+ for (const value of labels) {
8
+ const label = value.trim().replace(/\s+/g, " ");
9
+ if (!label) continue;
10
+ const key = label.toLowerCase();
11
+ if (seen.has(key)) continue;
12
+ seen.add(key);
13
+ result.push(label);
14
+ }
15
+ return result;
16
+ }
17
+
18
+ /** Match category filters independent of outer spacing and letter case. */
19
+ export function categoryKey(value: string): string {
20
+ return value.trim().replace(/\s+/g, " ").toLowerCase();
21
+ }
22
+
23
+ /** New native forms use comma-separated text; older schemas stored JSON arrays. */
24
+ export function readCategories(value: unknown): string[] {
25
+ if (value == null || value === "") return [];
26
+ if (typeof value === "string" && value.trim().startsWith("["))
27
+ value = JSON.parse(value);
28
+ if (typeof value === "string") return normalizeCategories(value);
29
+ if (!Array.isArray(value) || value.some(item => typeof item !== "string"))
30
+ reject("Categories must be comma-separated text or an array of names.");
31
+ return normalizeCategories(value);
32
+ }