@sdxc/kit 2026.10.17 → 2026.10.20
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/README.md +390 -20
- package/changelog.jsonl +1160 -1092
- package/config.schema.json +47 -1
- package/dist/cli.js +12 -0
- package/dist/commands/deploy.d.ts +23 -0
- package/dist/commands/deploy.js +167 -0
- package/dist/commands/destroy.d.ts +22 -0
- package/dist/commands/destroy.js +92 -0
- package/dist/commands/doctor.d.ts +26 -0
- package/dist/commands/doctor.js +65 -0
- package/dist/commands/initializers.d.ts +16 -0
- package/dist/commands/initializers.js +23 -0
- package/dist/commands/make.d.ts +72 -6
- package/dist/commands/make.js +127 -19
- package/dist/commands/middleware.d.ts +16 -0
- package/dist/commands/middleware.js +21 -0
- package/dist/commands/models.d.ts +18 -0
- package/dist/commands/models.js +29 -0
- package/dist/commands/notes.d.ts +17 -0
- package/dist/commands/notes.js +27 -0
- package/dist/commands/routes.d.ts +25 -0
- package/dist/commands/routes.js +50 -0
- package/dist/commands/run.d.ts +16 -0
- package/dist/commands/run.js +32 -11
- package/dist/commands/scaffold.d.ts +29 -0
- package/dist/commands/scaffold.js +33 -0
- package/dist/commands/schedule.d.ts +16 -0
- package/dist/commands/schedule.js +21 -0
- package/dist/commands/stats.d.ts +16 -0
- package/dist/commands/stats.js +21 -0
- package/dist/commands/ui/update.d.ts +6 -3
- package/dist/commands/ui/update.js +24 -7
- package/dist/commands/upgrade.d.ts +3 -1
- package/dist/commands/upgrade.js +88 -23
- package/dist/config.d.ts +18 -0
- package/dist/config.js +28 -1
- package/dist/contract.d.ts +97 -3
- package/dist/contract.js +360 -26
- package/dist/create/templates.js +3 -2
- package/dist/dependencies.d.ts +4 -1
- package/dist/dependencies.js +13 -1
- package/dist/deploy/plan.d.ts +49 -0
- package/dist/deploy/plan.js +68 -0
- package/dist/destroy.d.ts +40 -0
- package/dist/destroy.js +311 -0
- package/dist/doctor/check.d.ts +71 -0
- package/dist/doctor/check.js +53 -0
- package/dist/doctor/checks.d.ts +23 -0
- package/dist/doctor/checks.js +68 -0
- package/dist/doctor/define.d.ts +59 -0
- package/dist/doctor/define.js +16 -0
- package/dist/doctor/emails.d.ts +18 -0
- package/dist/doctor/emails.js +243 -0
- package/dist/doctor/env.d.ts +26 -0
- package/dist/doctor/env.js +88 -0
- package/dist/doctor/files.d.ts +14 -0
- package/dist/doctor/files.js +34 -0
- package/dist/doctor/fixture.d.ts +23 -0
- package/dist/doctor/fixture.js +46 -0
- package/dist/doctor/install.d.ts +17 -0
- package/dist/doctor/install.js +37 -0
- package/dist/doctor/installed.d.ts +11 -0
- package/dist/doctor/installed.js +79 -0
- package/dist/doctor/layout.d.ts +23 -0
- package/dist/doctor/layout.js +83 -0
- package/dist/doctor/migrations.d.ts +16 -0
- package/dist/doctor/migrations.js +96 -0
- package/dist/doctor/models.d.ts +13 -0
- package/dist/doctor/models.js +69 -0
- package/dist/doctor/pins.d.ts +15 -0
- package/dist/doctor/pins.js +79 -0
- package/dist/doctor/project.d.ts +58 -0
- package/dist/doctor/project.js +261 -0
- package/dist/doctor/remix.d.ts +14 -0
- package/dist/doctor/remix.js +44 -0
- package/dist/doctor/routes.d.ts +11 -0
- package/dist/doctor/routes.js +49 -0
- package/dist/doctor/typegen.d.ts +13 -0
- package/dist/doctor/typegen.js +57 -0
- package/dist/doctor/ui.d.ts +14 -0
- package/dist/doctor/ui.js +51 -0
- package/dist/initializers.d.ts +25 -0
- package/dist/initializers.js +89 -0
- package/dist/lock.d.ts +2 -2
- package/dist/make/actions.d.ts +23 -0
- package/dist/make/actions.js +82 -0
- package/dist/make/declare.d.ts +31 -3
- package/dist/make/declare.js +284 -9
- package/dist/make/email.d.ts +23 -0
- package/dist/make/email.js +111 -0
- package/dist/make/from-fields.d.ts +30 -0
- package/dist/make/from-fields.js +162 -0
- package/dist/make/from-model.d.ts +39 -0
- package/dist/make/from-model.js +161 -0
- package/dist/make/generate.d.ts +16 -5
- package/dist/make/generate.js +38 -15
- package/dist/make/guard.d.ts +35 -0
- package/dist/make/guard.js +73 -0
- package/dist/make/imports.d.ts +6 -0
- package/dist/make/imports.js +19 -0
- package/dist/make/index.d.ts +47 -4
- package/dist/make/index.js +287 -29
- package/dist/make/kinds.d.ts +29 -2
- package/dist/make/kinds.js +79 -7
- package/dist/make/mount.d.ts +25 -0
- package/dist/make/mount.js +135 -0
- package/dist/make/schema-diff.d.ts +58 -0
- package/dist/make/schema-diff.js +609 -0
- package/dist/make/schema.d.ts +76 -0
- package/dist/make/schema.js +206 -0
- package/dist/make/stubs.d.ts +7 -5
- package/dist/make/stubs.js +16 -5
- package/dist/make/test.d.ts +43 -0
- package/dist/make/test.js +149 -0
- package/dist/make/trigger.d.ts +31 -0
- package/dist/make/trigger.js +163 -0
- package/dist/models.d.ts +42 -0
- package/dist/models.js +149 -0
- package/dist/notes.d.ts +28 -0
- package/dist/notes.js +66 -0
- package/dist/reference.d.ts +27 -0
- package/dist/reference.js +103 -0
- package/dist/releases.d.ts +9 -0
- package/dist/releases.js +29 -8
- package/dist/routes/chains.d.ts +34 -0
- package/dist/routes/chains.js +95 -0
- package/dist/routes/filter.d.ts +53 -0
- package/dist/routes/filter.js +147 -0
- package/dist/routes/format.d.ts +23 -0
- package/dist/routes/format.js +123 -0
- package/dist/routes/helpers.d.ts +21 -0
- package/dist/routes/helpers.js +165 -0
- package/dist/routes/index.d.ts +56 -0
- package/dist/routes/index.js +167 -0
- package/dist/routes/modules.d.ts +116 -0
- package/dist/routes/modules.js +235 -0
- package/dist/routes/parse.d.ts +161 -0
- package/dist/routes/parse.js +621 -0
- package/dist/routes/routers.d.ts +69 -0
- package/dist/routes/routers.js +327 -0
- package/dist/scaffold/fields.d.ts +129 -0
- package/dist/scaffold/fields.js +421 -0
- package/dist/scaffold/index.d.ts +37 -0
- package/dist/scaffold/index.js +613 -0
- package/dist/scaffold/render.d.ts +51 -0
- package/dist/scaffold/render.js +332 -0
- package/dist/schedule.d.ts +45 -0
- package/dist/schedule.js +124 -0
- package/dist/stats.d.ts +37 -0
- package/dist/stats.js +126 -0
- package/dist/ui/commands.d.ts +10 -3
- package/dist/ui/commands.js +85 -15
- package/dist/ui/registry.d.ts +8 -8
- package/dist/upgrade/agents.d.ts +49 -0
- package/dist/upgrade/agents.js +110 -0
- package/dist/upgrade/changelog.d.ts +2 -2
- package/dist/upgrade/project.d.ts +4 -0
- package/dist/upgrade/project.js +11 -1
- package/dist/upgrade/prompt.d.ts +11 -0
- package/dist/upgrade/prompt.js +50 -7
- package/package.json +6 -4
- package/registry/ui/alert-dialog.json +2 -2
- package/registry/ui/attachment.json +2 -2
- package/registry/ui/calendar.json +2 -2
- package/registry/ui/color-picker.json +2 -2
- package/registry/ui/command.json +2 -2
- package/registry/ui/date-picker.json +2 -2
- package/registry/ui/date-range-picker.json +2 -2
- package/registry/ui/dialog.json +2 -2
- package/registry/ui/file-trigger.json +2 -2
- package/registry/ui/heading-scope.json +2 -2
- package/registry/ui/message-scroller.json +2 -2
- package/registry/ui/number-field.json +2 -2
- package/registry/ui/range-calendar.json +2 -2
- package/registry/ui/resizable.json +2 -2
- package/registry/ui/select.json +2 -2
- package/registry/ui/shared-element.json +2 -2
- package/stubs/controller.api.resource.stub +23 -0
- package/stubs/controller.form.stub +2 -2
- package/stubs/controller.form.test.stub +2 -2
- package/stubs/controller.resource.form.stub +67 -0
- package/stubs/controller.resource.stub +28 -0
- package/stubs/email.stub +9 -14
- package/stubs/email.test.stub +9 -9
- package/stubs/factory.stub +1 -1
- package/stubs/model.stub +3 -3
- package/stubs/policy.test.stub +34 -8
- package/stubs/scaffold.api.create.stub +34 -0
- package/stubs/scaffold.api.create.test.stub +37 -0
- package/stubs/scaffold.api.destroy.stub +34 -0
- package/stubs/scaffold.api.destroy.test.stub +44 -0
- package/stubs/scaffold.api.index.stub +23 -0
- package/stubs/scaffold.api.index.test.stub +31 -0
- package/stubs/scaffold.api.show.stub +27 -0
- package/stubs/scaffold.api.show.test.stub +41 -0
- package/stubs/scaffold.api.update.stub +44 -0
- package/stubs/scaffold.api.update.test.stub +46 -0
- package/stubs/scaffold.command.create.stub +22 -0
- package/stubs/scaffold.command.create.test.stub +30 -0
- package/stubs/scaffold.command.delete.stub +20 -0
- package/stubs/scaffold.command.delete.test.stub +39 -0
- package/stubs/scaffold.command.list.stub +18 -0
- package/stubs/scaffold.command.list.test.stub +31 -0
- package/stubs/scaffold.command.show.stub +19 -0
- package/stubs/scaffold.command.show.test.stub +37 -0
- package/stubs/scaffold.controller.destroy.stub +35 -0
- package/stubs/scaffold.controller.destroy.test.stub +65 -0
- package/stubs/scaffold.controller.edit.stub +97 -0
- package/stubs/scaffold.controller.edit.test.stub +91 -0
- package/stubs/scaffold.controller.index.stub +55 -0
- package/stubs/scaffold.controller.index.test.stub +32 -0
- package/stubs/scaffold.controller.new.stub +70 -0
- package/stubs/scaffold.controller.new.test.stub +81 -0
- package/stubs/scaffold.controller.show.stub +59 -0
- package/stubs/scaffold.controller.show.test.stub +43 -0
- package/stubs/scaffold.factory.stub +16 -0
- package/stubs/scaffold.form.stub +75 -0
- package/stubs/scaffold.mcp.create.stub +24 -0
- package/stubs/scaffold.mcp.create.test.stub +36 -0
- package/stubs/scaffold.mcp.delete.stub +31 -0
- package/stubs/scaffold.mcp.delete.test.stub +43 -0
- package/stubs/scaffold.mcp.get.stub +21 -0
- package/stubs/scaffold.mcp.get.test.stub +31 -0
- package/stubs/scaffold.mcp.list.stub +23 -0
- package/stubs/scaffold.mcp.list.test.stub +25 -0
- package/stubs/scaffold.mcp.update.stub +37 -0
- package/stubs/scaffold.mcp.update.test.stub +40 -0
- package/stubs/scaffold.migration.stub +2 -0
- package/stubs/scaffold.model.stub +35 -0
- package/stubs/scaffold.model.test.stub +25 -0
- package/stubs/scaffold.test-database.stub +33 -0
- package/stubs/scaffold.test-mcp.stub +92 -0
- package/stubs/scaffold.validator.stub +18 -0
- package/stubs/scaffold.validator.test.stub +26 -0
- package/templates/app/AGENTS.md +163 -0
- package/templates/app/CLAUDE.md +1 -0
- package/templates/app/README.md +28 -13
- package/templates/app/app/commands/console.test.ts +26 -0
- package/templates/app/app/commands/console.ts +19 -0
- package/templates/app/app/commands/db/fresh.test.ts +57 -0
- package/templates/app/app/commands/db/fresh.ts +37 -0
- package/templates/app/app/commands/db/migrate.test.ts +17 -1
- package/templates/app/app/commands/db/migrate.ts +51 -18
- package/templates/app/app/commands/db/prepare.test.ts +39 -0
- package/templates/app/app/commands/db/prepare.ts +35 -0
- package/templates/app/app/commands/db/seed.test.ts +38 -0
- package/templates/app/app/commands/db/seed.ts +26 -0
- package/templates/app/app/commands/deploy.test.ts +34 -0
- package/templates/app/app/commands/deploy.ts +18 -0
- package/templates/app/app/commands/emails/preview.test.tsx +63 -0
- package/templates/app/app/commands/emails/preview.ts +24 -0
- package/templates/app/app/commands/index.ts +57 -2
- package/templates/app/app/emails/index.ts +10 -0
- package/templates/app/app/http/middleware/access.test.ts +43 -0
- package/templates/app/app/http/middleware/access.ts +41 -0
- package/templates/app/app/http/middleware/api.ts +12 -3
- package/templates/app/app/http/middleware/page.test.ts +4 -1
- package/templates/app/app/http/middleware/page.ts +7 -5
- package/templates/app/app/initializers/cli.ts +28 -2
- package/templates/app/app/initializers/dispatcher.ts +9 -1
- package/templates/app/app/initializers/mail-transport.test.ts +27 -0
- package/templates/app/app/initializers/mail-transport.ts +26 -0
- package/templates/app/app/initializers/mail.test.ts +17 -17
- package/templates/app/app/initializers/mail.ts +15 -7
- package/templates/app/app/initializers/router.test.ts +7 -0
- package/templates/app/app/initializers/router.tsx +13 -3
- package/templates/app/app/jobs/email.test.tsx +70 -0
- package/templates/app/app/jobs/email.ts +16 -0
- package/templates/app/app/jobs/index.ts +6 -2
- package/templates/app/app/policies/abilities.ts +13 -0
- package/templates/app/app/policies/policy.test.ts +15 -0
- package/templates/app/app/policies/policy.ts +30 -0
- package/templates/app/app/services/commands.ts +30 -0
- package/templates/app/app/services/migrations.test.ts +48 -1
- package/templates/app/app/services/migrations.ts +66 -9
- package/templates/app/app/test/local-database.ts +67 -0
- package/templates/app/app/test/session.ts +28 -0
- package/templates/app/bootstrap/console.ts +13 -0
- package/templates/app/cloudflare.config.ts +3 -3
- package/templates/app/database/seed.ts +12 -0
- package/templates/app/package.json +2 -1
- package/stubs/policy.stub +0 -16
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SQLite DDL for a `remix/data-table` table: the `CREATE TABLE` a model's table needs, its unique
|
|
3
|
+
* indexes, and the column clauses `ALTER TABLE` reuses. One renderer serves `make migration
|
|
4
|
+
* --from-model` and every generator that writes a table, so a table is spelled one way everywhere.
|
|
5
|
+
*
|
|
6
|
+
* @author [Sergio Xalambrí](https://sergiodxa.com)
|
|
7
|
+
* @copyright Sergio Xalambrí 2026
|
|
8
|
+
*/
|
|
9
|
+
/** The description data-table gives the symbol it keeps a table's metadata under. */
|
|
10
|
+
const TABLE_METADATA = "data-table.tableMetadata";
|
|
11
|
+
/**
|
|
12
|
+
* SQLite's storage class for each data-table type. Dates and times are ISO text, JSON is text,
|
|
13
|
+
* booleans are 0 and 1, and a decimal keeps NUMERIC affinity so `1.50` reads back as a number.
|
|
14
|
+
*/
|
|
15
|
+
const SQLITE_TYPES = {
|
|
16
|
+
varchar: "TEXT",
|
|
17
|
+
text: "TEXT",
|
|
18
|
+
uuid: "TEXT",
|
|
19
|
+
enum: "TEXT",
|
|
20
|
+
json: "TEXT",
|
|
21
|
+
date: "TEXT",
|
|
22
|
+
time: "TEXT",
|
|
23
|
+
timestamp: "TEXT",
|
|
24
|
+
integer: "INTEGER",
|
|
25
|
+
bigint: "INTEGER",
|
|
26
|
+
boolean: "INTEGER",
|
|
27
|
+
decimal: "NUMERIC",
|
|
28
|
+
binary: "BLOB",
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* The shape of a data-table table, or `null` for anything else. The metadata is found by its
|
|
32
|
+
* symbol's description, so a table built by the project's own copy of `remix/data-table` reads
|
|
33
|
+
* the same as one built by this package's copy.
|
|
34
|
+
*/
|
|
35
|
+
export function tableShape(value) {
|
|
36
|
+
if (value === null || (typeof value !== "object" && typeof value !== "function"))
|
|
37
|
+
return null;
|
|
38
|
+
let symbol = Object.getOwnPropertySymbols(value).find((candidate) => candidate.description === TABLE_METADATA);
|
|
39
|
+
if (symbol === undefined)
|
|
40
|
+
return null;
|
|
41
|
+
let metadata = value[symbol];
|
|
42
|
+
if (typeof metadata?.name !== "string" || !Array.isArray(metadata.primaryKey))
|
|
43
|
+
return null;
|
|
44
|
+
if (typeof metadata.columnDefinitions !== "object" || metadata.columnDefinitions === null) {
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
return {
|
|
48
|
+
name: metadata.name,
|
|
49
|
+
primaryKey: metadata.primaryKey.map(String),
|
|
50
|
+
columns: metadata.columnDefinitions,
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* The SQL that creates `table` on an empty database: its `CREATE TABLE`, then a `CREATE UNIQUE
|
|
55
|
+
* INDEX` per `.unique()` column, each statement ending in `;` and separated by a blank line.
|
|
56
|
+
* Every column is `NOT NULL` unless declared `.nullable()`, as data-table types its rows.
|
|
57
|
+
*
|
|
58
|
+
* @example createTableStatement(postsTable)
|
|
59
|
+
*/
|
|
60
|
+
export function createTableStatement(table) {
|
|
61
|
+
let shape = tableShape(table) ?? table;
|
|
62
|
+
return [createTable(shape), ...uniqueIndexes(shape)].join("\n\n");
|
|
63
|
+
}
|
|
64
|
+
/** The `CREATE TABLE` statement alone, under `name` when the table is built beside its original. */
|
|
65
|
+
export function createTable(table, name = table.name) {
|
|
66
|
+
let composite = table.primaryKey.length > 1;
|
|
67
|
+
let lines = Object.entries(table.columns).map(([column, definition]) => ` ${columnClause(table, column, definition, { inlineKey: !composite })}`);
|
|
68
|
+
if (composite)
|
|
69
|
+
lines.push(` PRIMARY KEY (${table.primaryKey.map(quote).join(", ")})`);
|
|
70
|
+
for (let [column, definition] of Object.entries(table.columns)) {
|
|
71
|
+
let { references } = definition;
|
|
72
|
+
if (references === undefined)
|
|
73
|
+
continue;
|
|
74
|
+
lines.push(` CONSTRAINT ${quote(references.name)} FOREIGN KEY (${quote(column)}) ${referencesClause(definition)}`);
|
|
75
|
+
}
|
|
76
|
+
for (let check of checksOf(table)) {
|
|
77
|
+
lines.push(` CONSTRAINT ${quote(check.name)} CHECK (${check.expression})`);
|
|
78
|
+
}
|
|
79
|
+
return `CREATE TABLE ${quote(name)} (\n${lines.join(",\n")}\n);`;
|
|
80
|
+
}
|
|
81
|
+
/** One `CREATE UNIQUE INDEX` per `.unique()` column of `table`. */
|
|
82
|
+
export function uniqueIndexes(table) {
|
|
83
|
+
return Object.entries(table.columns)
|
|
84
|
+
.filter(([, definition]) => definition.unique !== undefined && definition.unique !== false)
|
|
85
|
+
.map(([column]) => uniqueIndex(table, column));
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* The unique index `.unique(name)` names, or `<table>_<column>_unique`. An index keeps the
|
|
89
|
+
* column addable with `ALTER TABLE ADD COLUMN`, which refuses an inline `UNIQUE`.
|
|
90
|
+
*/
|
|
91
|
+
export function uniqueIndex(table, column) {
|
|
92
|
+
let unique = table.columns[column]?.unique;
|
|
93
|
+
let named = typeof unique === "object" ? unique.name : undefined;
|
|
94
|
+
let name = named ?? `${table.name}_${column}_unique`;
|
|
95
|
+
return `CREATE UNIQUE INDEX ${quote(name)} ON ${quote(table.name)} (${quote(column)});`;
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* The column's definition: name, type, key, nullability, default, collation and generation, plus
|
|
99
|
+
* its foreign key and checks when `constraints` asks for them.
|
|
100
|
+
*/
|
|
101
|
+
export function columnClause(table, column, definition, options = {}) {
|
|
102
|
+
let parts = [quote(column), sqliteType(definition.type)];
|
|
103
|
+
let key = isKey(table, column);
|
|
104
|
+
if (key && options.inlineKey === true) {
|
|
105
|
+
parts.push("PRIMARY KEY");
|
|
106
|
+
if (autoIncrements(table, column))
|
|
107
|
+
parts.push("AUTOINCREMENT");
|
|
108
|
+
}
|
|
109
|
+
if (isNotNull(table, column))
|
|
110
|
+
parts.push("NOT NULL");
|
|
111
|
+
let fallback = defaultClause(definition);
|
|
112
|
+
if (fallback !== null && definition.computed === undefined)
|
|
113
|
+
parts.push(`DEFAULT ${fallback}`);
|
|
114
|
+
if (definition.collate !== undefined)
|
|
115
|
+
parts.push(`COLLATE ${quote(definition.collate)}`);
|
|
116
|
+
if (definition.computed !== undefined) {
|
|
117
|
+
let storage = definition.computed.stored ? "STORED" : "VIRTUAL";
|
|
118
|
+
parts.push(`GENERATED ALWAYS AS (${definition.computed.expression}) ${storage}`);
|
|
119
|
+
}
|
|
120
|
+
if (options.constraints === true) {
|
|
121
|
+
if (definition.references !== undefined) {
|
|
122
|
+
parts.push(`CONSTRAINT ${quote(definition.references.name)} ${referencesClause(definition)}`);
|
|
123
|
+
}
|
|
124
|
+
for (let check of definition.checks ?? []) {
|
|
125
|
+
parts.push(`CONSTRAINT ${quote(check.name)} CHECK (${check.expression})`);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
return parts.join(" ");
|
|
129
|
+
}
|
|
130
|
+
/** The SQLite type a data-table column type is declared with. */
|
|
131
|
+
export function sqliteType(type) {
|
|
132
|
+
return SQLITE_TYPES[type] ?? "TEXT";
|
|
133
|
+
}
|
|
134
|
+
/** Whether `column` is part of the table's primary key; names compare as SQLite does, ignoring case. */
|
|
135
|
+
export function isKey(table, column) {
|
|
136
|
+
return table.primaryKey.some((key) => key.toLowerCase() === column.toLowerCase());
|
|
137
|
+
}
|
|
138
|
+
/** Whether the column refuses `NULL`: a key column always does, any other unless `.nullable()`. */
|
|
139
|
+
export function isNotNull(table, column) {
|
|
140
|
+
return isKey(table, column) || table.columns[column]?.nullable !== true;
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* The default's SQL, or `null` without one. A literal becomes a SQL literal (booleans as 0 and 1,
|
|
144
|
+
* dates as ISO text, objects as JSON text), `defaultNow()` becomes `CURRENT_TIMESTAMP`, and a
|
|
145
|
+
* `defaultSql()` expression is wrapped in parentheses, as SQLite requires of an expression.
|
|
146
|
+
*/
|
|
147
|
+
export function defaultClause(definition) {
|
|
148
|
+
let fallback = definition.default;
|
|
149
|
+
if (fallback === undefined)
|
|
150
|
+
return null;
|
|
151
|
+
if (fallback.kind === "now")
|
|
152
|
+
return "CURRENT_TIMESTAMP";
|
|
153
|
+
if (fallback.kind === "sql")
|
|
154
|
+
return `(${fallback.expression})`;
|
|
155
|
+
return literal(fallback.value);
|
|
156
|
+
}
|
|
157
|
+
/** `value` as a SQL literal. */
|
|
158
|
+
export function literal(value) {
|
|
159
|
+
if (value === null || value === undefined)
|
|
160
|
+
return "NULL";
|
|
161
|
+
if (typeof value === "boolean")
|
|
162
|
+
return value ? "1" : "0";
|
|
163
|
+
if (typeof value === "number" || typeof value === "bigint")
|
|
164
|
+
return String(value);
|
|
165
|
+
if (value instanceof Date)
|
|
166
|
+
return text(value.toISOString());
|
|
167
|
+
if (typeof value === "string")
|
|
168
|
+
return text(value);
|
|
169
|
+
return text(JSON.stringify(value));
|
|
170
|
+
}
|
|
171
|
+
/** `value` as a single-quoted SQL string. */
|
|
172
|
+
function text(value) {
|
|
173
|
+
return `'${value.replaceAll("'", "''")}'`;
|
|
174
|
+
}
|
|
175
|
+
/** `name` as a double-quoted SQL identifier, which SQLite reads as a name and never as text. */
|
|
176
|
+
export function quote(name) {
|
|
177
|
+
return `"${name.replaceAll('"', '""')}"`;
|
|
178
|
+
}
|
|
179
|
+
/** Every check declared on the table's columns, in column order. */
|
|
180
|
+
export function checksOf(table) {
|
|
181
|
+
return Object.values(table.columns).flatMap((definition) => definition.checks ?? []);
|
|
182
|
+
}
|
|
183
|
+
/** The `REFERENCES` clause of a column's foreign key, with its actions. */
|
|
184
|
+
function referencesClause(definition) {
|
|
185
|
+
let references = definition.references;
|
|
186
|
+
if (references === undefined)
|
|
187
|
+
return "";
|
|
188
|
+
let clause = `REFERENCES ${quote(references.table.name)} (${references.columns.map(quote).join(", ")})`;
|
|
189
|
+
if (references.onDelete !== undefined)
|
|
190
|
+
clause += ` ON DELETE ${references.onDelete.toUpperCase()}`;
|
|
191
|
+
if (references.onUpdate !== undefined)
|
|
192
|
+
clause += ` ON UPDATE ${references.onUpdate.toUpperCase()}`;
|
|
193
|
+
return clause;
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Whether the column is written `INTEGER PRIMARY KEY AUTOINCREMENT`: SQLite allows it only on a
|
|
197
|
+
* single-column integer key, so `.autoIncrement()` or `.identity()` anywhere else is left out.
|
|
198
|
+
*/
|
|
199
|
+
function autoIncrements(table, column) {
|
|
200
|
+
let definition = table.columns[column];
|
|
201
|
+
if (definition === undefined || table.primaryKey.length !== 1)
|
|
202
|
+
return false;
|
|
203
|
+
if (sqliteType(definition.type) !== "INTEGER")
|
|
204
|
+
return false;
|
|
205
|
+
return definition.autoIncrement === true || definition.identity !== undefined;
|
|
206
|
+
}
|
package/dist/make/stubs.d.ts
CHANGED
|
@@ -33,12 +33,14 @@ export declare function builtinStubsDir(packageRoot: string): string;
|
|
|
33
33
|
*/
|
|
34
34
|
export declare function loadStub(names: readonly string[], root: string, stubsDir: string, packageRoot: string): Promise<Result<Stub, Error>>;
|
|
35
35
|
/**
|
|
36
|
-
* `stub`'s text with every placeholder replaced by its value. A
|
|
37
|
-
*
|
|
36
|
+
* `stub`'s text with every placeholder replaced by its value. A multi-line value standing alone
|
|
37
|
+
* on an indented line takes that indentation on every line, so a block lands at its depth. A
|
|
38
|
+
* placeholder without a value is a failure naming the stub, the placeholder and the ones accepted.
|
|
38
39
|
*/
|
|
39
40
|
export declare function renderStub(stub: Stub, values: Readonly<Record<string, string>>): Result<string, Error>;
|
|
40
41
|
/**
|
|
41
|
-
* Copies the built-in stubs of `kinds` (
|
|
42
|
-
* creating it. A stub already there is kept as it is, so a project's
|
|
42
|
+
* Copies the built-in stubs of `kinds`, each a kind or `scaffold` (every stub when empty), into
|
|
43
|
+
* the project's `stubsDir`, creating it. A stub already there is kept as it is, so a project's
|
|
44
|
+
* edits survive.
|
|
43
45
|
*/
|
|
44
|
-
export declare function copyStubs(kinds: readonly
|
|
46
|
+
export declare function copyStubs(kinds: readonly string[], root: string, stubsDir: string, packageRoot: string): Promise<Result<CopiedStubs, Error>>;
|
package/dist/make/stubs.js
CHANGED
|
@@ -41,8 +41,9 @@ export async function loadStub(names, root, stubsDir, packageRoot) {
|
|
|
41
41
|
return failure(new Error(`No stub ${names.join(" or ")} in ${stubsDir} or @sdxc/kit`));
|
|
42
42
|
}
|
|
43
43
|
/**
|
|
44
|
-
* `stub`'s text with every placeholder replaced by its value. A
|
|
45
|
-
*
|
|
44
|
+
* `stub`'s text with every placeholder replaced by its value. A multi-line value standing alone
|
|
45
|
+
* on an indented line takes that indentation on every line, so a block lands at its depth. A
|
|
46
|
+
* placeholder without a value is a failure naming the stub, the placeholder and the ones accepted.
|
|
46
47
|
*/
|
|
47
48
|
export function renderStub(stub, values) {
|
|
48
49
|
let unknown = [...stub.text.matchAll(PLACEHOLDER)]
|
|
@@ -54,11 +55,21 @@ export function renderStub(stub, values) {
|
|
|
54
55
|
.join(", ");
|
|
55
56
|
return failure(new Error(`${stub.source} uses {{${unknown[0]}}}, which this kind does not define; it accepts ${accepted}`));
|
|
56
57
|
}
|
|
57
|
-
return success(stub.text.replace(PLACEHOLDER, (
|
|
58
|
+
return success(stub.text.replace(PLACEHOLDER, (match, name, offset) => {
|
|
59
|
+
let value = values[name] ?? "";
|
|
60
|
+
let start = stub.text.lastIndexOf("\n", offset - 1) + 1;
|
|
61
|
+
let indent = stub.text.slice(start, offset);
|
|
62
|
+
let end = stub.text.indexOf("\n", offset);
|
|
63
|
+
let rest = stub.text.slice(offset + match.length, end === -1 ? undefined : end);
|
|
64
|
+
if (!/^[ \t]+$/.test(indent) || rest.trim() !== "")
|
|
65
|
+
return value;
|
|
66
|
+
return value.replaceAll(/\n(?=.)/g, `\n${indent}`);
|
|
67
|
+
}));
|
|
58
68
|
}
|
|
59
69
|
/**
|
|
60
|
-
* Copies the built-in stubs of `kinds` (
|
|
61
|
-
* creating it. A stub already there is kept as it is, so a project's
|
|
70
|
+
* Copies the built-in stubs of `kinds`, each a kind or `scaffold` (every stub when empty), into
|
|
71
|
+
* the project's `stubsDir`, creating it. A stub already there is kept as it is, so a project's
|
|
72
|
+
* edits survive.
|
|
62
73
|
*/
|
|
63
74
|
export async function copyStubs(kinds, root, stubsDir, packageRoot) {
|
|
64
75
|
let builtin = await wrap(() => readdir(builtinStubsDir(packageRoot)));
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `sdxc make test <file>`: the test `sdxc make` writes beside a file of its kind, for a file
|
|
3
|
+
* that has none, such as one made with `--no-test`. The kind comes from the folder the file
|
|
4
|
+
* sits in, and a controller's route from the router that maps it.
|
|
5
|
+
*
|
|
6
|
+
* @author [Sergio Xalambrí](https://sergiodxa.com)
|
|
7
|
+
* @copyright Sergio Xalambrí 2026
|
|
8
|
+
*/
|
|
9
|
+
import type { Result } from "@sdxc/result";
|
|
10
|
+
import type { Project } from "../middleware.js";
|
|
11
|
+
import type { KindName } from "./kinds.js";
|
|
12
|
+
import type { MakeContext } from "./index.js";
|
|
13
|
+
/** What `make test` was asked for. */
|
|
14
|
+
export interface MakeTestInput {
|
|
15
|
+
/** The file to test, relative to the project root or to the current directory. */
|
|
16
|
+
file: string;
|
|
17
|
+
/** The folder relative paths resolve against. */
|
|
18
|
+
cwd: string;
|
|
19
|
+
dryRun: boolean;
|
|
20
|
+
/** Replace a test that exists already. */
|
|
21
|
+
force: boolean;
|
|
22
|
+
}
|
|
23
|
+
/** The kind a file belongs to, read from the folder it sits in. */
|
|
24
|
+
interface Located {
|
|
25
|
+
kind: KindName;
|
|
26
|
+
/** The file's path inside the kind's folder, without its extension. */
|
|
27
|
+
name: string;
|
|
28
|
+
variant: string | null;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* The kind whose folder holds `path`, and the name inside it. Migrations, factories and
|
|
32
|
+
* policies get no test from here: the first two never have one, and a policy's test is written
|
|
33
|
+
* with its abilities by `sdxc make policy`.
|
|
34
|
+
*/
|
|
35
|
+
export declare function locate(path: string): Result<Located, Error>;
|
|
36
|
+
/**
|
|
37
|
+
* Writes the test for `input.file` from its kind's test stub, printing the path, or the whole
|
|
38
|
+
* test under `dryRun`. An existing test stops the run unless `force` replaces it.
|
|
39
|
+
*
|
|
40
|
+
* @param packageRoot - The `@sdxc/kit` package, whose `stubs/` holds the built-in stubs.
|
|
41
|
+
*/
|
|
42
|
+
export declare function makeTest(ctx: MakeContext, project: Project, packageRoot: string, input: MakeTestInput): Promise<Result<void, Error>>;
|
|
43
|
+
export {};
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `sdxc make test <file>`: the test `sdxc make` writes beside a file of its kind, for a file
|
|
3
|
+
* that has none, such as one made with `--no-test`. The kind comes from the folder the file
|
|
4
|
+
* sits in, and a controller's route from the router that maps it.
|
|
5
|
+
*
|
|
6
|
+
* @author [Sergio Xalambrí](https://sergiodxa.com)
|
|
7
|
+
* @copyright Sergio Xalambrí 2026
|
|
8
|
+
*/
|
|
9
|
+
import { mkdir, writeFile } from "node:fs/promises";
|
|
10
|
+
import { dirname, join, relative } from "node:path";
|
|
11
|
+
import { failure, isFailure, success, wrap } from "@sdxc/result";
|
|
12
|
+
import { missingDependencies } from "../dependencies.js";
|
|
13
|
+
import { formatFiles } from "../format.js";
|
|
14
|
+
import { lockFileAtOrAbove, packageManager } from "../package-manager.js";
|
|
15
|
+
import { listRoutes } from "../routes/index.js";
|
|
16
|
+
import { readManifest } from "../upgrade/project.js";
|
|
17
|
+
import { exists, plan } from "./generate.js";
|
|
18
|
+
import { KINDS, MCP_RESOURCES_FOLDER } from "./kinds.js";
|
|
19
|
+
import { parseName } from "./names.js";
|
|
20
|
+
/**
|
|
21
|
+
* The kind whose folder holds `path`, and the name inside it. Migrations, factories and
|
|
22
|
+
* policies get no test from here: the first two never have one, and a policy's test is written
|
|
23
|
+
* with its abilities by `sdxc make policy`.
|
|
24
|
+
*/
|
|
25
|
+
export function locate(path) {
|
|
26
|
+
let folders = [
|
|
27
|
+
[MCP_RESOURCES_FOLDER, "mcp", "resource"],
|
|
28
|
+
...Object.entries(KINDS).map(([kind, spec]) => [spec.folder, kind, null]),
|
|
29
|
+
];
|
|
30
|
+
for (let [folder, kind, variant] of folders) {
|
|
31
|
+
let spec = KINDS[kind];
|
|
32
|
+
if (!path.startsWith(`${folder}/`) || !path.endsWith(spec.extension))
|
|
33
|
+
continue;
|
|
34
|
+
if (path.endsWith(`.test${spec.extension}`)) {
|
|
35
|
+
return failure(new Error(`${path} is a test; name the file it tests`));
|
|
36
|
+
}
|
|
37
|
+
if (!spec.tests || spec.testOnly === true) {
|
|
38
|
+
let reason = kind === "policy"
|
|
39
|
+
? "a policy's test is written with its abilities by sdxc make policy"
|
|
40
|
+
: `a ${kind} has no test`;
|
|
41
|
+
return failure(new Error(`${path} gets no test from sdxc make test: ${reason}`));
|
|
42
|
+
}
|
|
43
|
+
return success({ kind, name: path.slice(folder.length + 1, -spec.extension.length), variant });
|
|
44
|
+
}
|
|
45
|
+
let known = Object.values(KINDS)
|
|
46
|
+
.filter((spec) => spec.tests && spec.testOnly !== true)
|
|
47
|
+
.map((spec) => spec.folder);
|
|
48
|
+
return failure(new Error(`${path} is in no folder sdxc make writes tests for; those are ${known.join(", ")} and ${MCP_RESOURCES_FOLDER}`));
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* The route a controller answers, from the routers that map it: its contract and key path,
|
|
52
|
+
* and whether it is a form (an `index` and an `action` under one key). A controller no router
|
|
53
|
+
* maps takes the key path its name spells in the configured contract.
|
|
54
|
+
*/
|
|
55
|
+
async function controllerRoute(root, file) {
|
|
56
|
+
let listing = await listRoutes(root);
|
|
57
|
+
let entries = listing.routes.filter((entry) => entry.controller?.file === file);
|
|
58
|
+
let first = entries[0];
|
|
59
|
+
if (first === undefined)
|
|
60
|
+
return { routes: null, path: null, form: false, pattern: "" };
|
|
61
|
+
let form = entries.find((entry) => entry.name.endsWith(".action"));
|
|
62
|
+
let path = form === undefined ? first.name : form.name.slice(0, -".action".length);
|
|
63
|
+
return { routes: first.contract, path, form: form !== undefined, pattern: first.pattern };
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Writes the test for `input.file` from its kind's test stub, printing the path, or the whole
|
|
67
|
+
* test under `dryRun`. An existing test stops the run unless `force` replaces it.
|
|
68
|
+
*
|
|
69
|
+
* @param packageRoot - The `@sdxc/kit` package, whose `stubs/` holds the built-in stubs.
|
|
70
|
+
*/
|
|
71
|
+
export async function makeTest(ctx, project, packageRoot, input) {
|
|
72
|
+
let { root, config } = project;
|
|
73
|
+
let file = relative(root, join(input.cwd, input.file)).split("\\").join("/");
|
|
74
|
+
if (file.startsWith(".."))
|
|
75
|
+
return failure(new Error(`${input.file} is outside the project`));
|
|
76
|
+
if (!(await exists(root, file))) {
|
|
77
|
+
return failure(new Error(`${file} does not exist; sdxc make test writes a test for a file`));
|
|
78
|
+
}
|
|
79
|
+
let located = locate(file);
|
|
80
|
+
if (isFailure(located))
|
|
81
|
+
return located;
|
|
82
|
+
let { kind, variant } = located.data;
|
|
83
|
+
let name = parseName(located.data.name);
|
|
84
|
+
if (isFailure(name))
|
|
85
|
+
return name;
|
|
86
|
+
let routes = config.make.routes;
|
|
87
|
+
let overrides = {};
|
|
88
|
+
let chosen = variant;
|
|
89
|
+
if (kind === "controller") {
|
|
90
|
+
let route = await controllerRoute(root, file);
|
|
91
|
+
if (route.routes !== null)
|
|
92
|
+
routes = route.routes;
|
|
93
|
+
if (route.path !== null)
|
|
94
|
+
overrides.path = route.path;
|
|
95
|
+
if (route.form)
|
|
96
|
+
chosen = "form";
|
|
97
|
+
let params = [...route.pattern.matchAll(/:(\w+)/g)].map((match) => match[1]);
|
|
98
|
+
if (params.length > 0) {
|
|
99
|
+
overrides.sampleParams = `{ ${params.map((param) => `${param}: "1"`).join(", ")} }`;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
let request = {
|
|
103
|
+
kind,
|
|
104
|
+
name: name.data,
|
|
105
|
+
variant: chosen,
|
|
106
|
+
tests: true,
|
|
107
|
+
routes,
|
|
108
|
+
replace: input.force,
|
|
109
|
+
testAlone: true,
|
|
110
|
+
};
|
|
111
|
+
let planned = await plan(request, root, config, packageRoot, overrides);
|
|
112
|
+
if (isFailure(planned))
|
|
113
|
+
return planned;
|
|
114
|
+
let dependencies = await missingDependencies(root, planned.data.files);
|
|
115
|
+
if (isFailure(dependencies))
|
|
116
|
+
return dependencies;
|
|
117
|
+
if (input.dryRun) {
|
|
118
|
+
for (let test of planned.data.files)
|
|
119
|
+
ctx.stdout(`Would write ${test.path}:\n\n${test.content}\n`);
|
|
120
|
+
return success(undefined);
|
|
121
|
+
}
|
|
122
|
+
let paths = [];
|
|
123
|
+
for (let test of planned.data.files) {
|
|
124
|
+
let replaced = await exists(root, test.path);
|
|
125
|
+
let target = join(root, test.path);
|
|
126
|
+
let written = await wrap(async () => {
|
|
127
|
+
await mkdir(dirname(target), { recursive: true });
|
|
128
|
+
await writeFile(target, test.content, { flag: input.force ? "w" : "wx" });
|
|
129
|
+
});
|
|
130
|
+
if (isFailure(written))
|
|
131
|
+
return written;
|
|
132
|
+
ctx.stdout(`${replaced ? "Replaced" : "Wrote"} ${test.path}\n`);
|
|
133
|
+
paths.push(test.path);
|
|
134
|
+
}
|
|
135
|
+
if (dependencies.data !== null) {
|
|
136
|
+
let edit = dependencies.data;
|
|
137
|
+
let edited = await wrap(() => writeFile(join(root, edit.path), edit.after));
|
|
138
|
+
if (isFailure(edited))
|
|
139
|
+
return edited;
|
|
140
|
+
let read = await readManifest(root);
|
|
141
|
+
let manager = await packageManager({
|
|
142
|
+
declared: isFailure(read) ? undefined : read.data.manifest.packageManager,
|
|
143
|
+
findLockFile: lockFileAtOrAbove(root),
|
|
144
|
+
});
|
|
145
|
+
let added = edit.added.map(({ name: dependency, version }) => `${dependency}@${version}`);
|
|
146
|
+
ctx.stdout(`Added ${added.join(", ")} to package.json; run ${manager.install.join(" ")}\n`);
|
|
147
|
+
}
|
|
148
|
+
return formatFiles(ctx, config.format, paths, root);
|
|
149
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Worker trigger behind a scheduled job: a cron job runs only when a trigger delivers its
|
|
3
|
+
* exact expression, so `make job --cron` adds `triggers.scheduled(…)` to `cloudflare.config.ts`
|
|
4
|
+
* and `destroy job` takes it out once no other job runs on it.
|
|
5
|
+
*
|
|
6
|
+
* @author [Sergio Xalambrí](https://sergiodxa.com)
|
|
7
|
+
* @copyright Sergio Xalambrí 2026
|
|
8
|
+
*/
|
|
9
|
+
import type { FileEdit } from "./declare.js";
|
|
10
|
+
/** What scheduling `cron` takes: the edit to `cloudflare.config.ts`, or a note to print. */
|
|
11
|
+
export interface TriggerPlan {
|
|
12
|
+
edit: FileEdit | null;
|
|
13
|
+
note: string | null;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Adds `triggers.scheduled({ schedule: cron })` to the `worker.triggers` list of
|
|
17
|
+
* `cloudflare.config.ts` unless a trigger already delivers the same schedule. A project
|
|
18
|
+
* configured in `wrangler.jsonc`, or whose config has no such list, gets a note instead, and a
|
|
19
|
+
* project with no Worker configuration at all gets neither.
|
|
20
|
+
*/
|
|
21
|
+
export declare function planTrigger(root: string, cron: string): Promise<TriggerPlan>;
|
|
22
|
+
/**
|
|
23
|
+
* `source`, the text of `cloudflare.config.ts`, without its scheduled triggers for `cron`, or
|
|
24
|
+
* `null` when it has none or does not scan.
|
|
25
|
+
*/
|
|
26
|
+
export declare function removeTrigger(source: string, cron: string): string | null;
|
|
27
|
+
/**
|
|
28
|
+
* What unscheduling `cron` takes once no remaining job runs on it: the edit to
|
|
29
|
+
* `cloudflare.config.ts`, and a note for each other file whose trigger still delivers it.
|
|
30
|
+
*/
|
|
31
|
+
export declare function planUntrigger(root: string, cron: string): Promise<TriggerPlan>;
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Worker trigger behind a scheduled job: a cron job runs only when a trigger delivers its
|
|
3
|
+
* exact expression, so `make job --cron` adds `triggers.scheduled(…)` to `cloudflare.config.ts`
|
|
4
|
+
* and `destroy job` takes it out once no other job runs on it.
|
|
5
|
+
*
|
|
6
|
+
* @author [Sergio Xalambrí](https://sergiodxa.com)
|
|
7
|
+
* @copyright Sergio Xalambrí 2026
|
|
8
|
+
*/
|
|
9
|
+
import { readFile } from "node:fs/promises";
|
|
10
|
+
import { join } from "node:path";
|
|
11
|
+
import { addElement, tokenize } from "@sdxc/codemod";
|
|
12
|
+
import { isFailure, wrap } from "@sdxc/result";
|
|
13
|
+
import { normalized, TRIGGER_FILES, triggerCrons } from "../schedule.js";
|
|
14
|
+
import { literal } from "./generate.js";
|
|
15
|
+
import { ensureImport } from "./imports.js";
|
|
16
|
+
/** The file `make` adds triggers to; the others in `TRIGGER_FILES` are edited by hand. */
|
|
17
|
+
const CONFIG = "cloudflare.config.ts";
|
|
18
|
+
/** The first of `TRIGGER_FILES` in the project, or `null` when it has none. */
|
|
19
|
+
async function triggerFile(root) {
|
|
20
|
+
for (let path of TRIGGER_FILES) {
|
|
21
|
+
let read = await wrap(() => readFile(join(root, path), "utf8"));
|
|
22
|
+
if (!isFailure(read))
|
|
23
|
+
return { path, source: read.data };
|
|
24
|
+
}
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
/** The note asking the user to add or remove `cron`'s trigger in `file`, saying why. */
|
|
28
|
+
function manualNote(action, file, cron, reason) {
|
|
29
|
+
let [where, line] = file === CONFIG
|
|
30
|
+
? ["worker.triggers", `triggers.scheduled({ schedule: ${literal(cron)} }),`]
|
|
31
|
+
: ["triggers.crons", literal(cron)];
|
|
32
|
+
return `${action} its trigger by hand, since ${reason}:\nIn ${file}, in ${where}:\n ${line}\n`;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Adds `triggers.scheduled({ schedule: cron })` to the `worker.triggers` list of
|
|
36
|
+
* `cloudflare.config.ts` unless a trigger already delivers the same schedule. A project
|
|
37
|
+
* configured in `wrangler.jsonc`, or whose config has no such list, gets a note instead, and a
|
|
38
|
+
* project with no Worker configuration at all gets neither.
|
|
39
|
+
*/
|
|
40
|
+
export async function planTrigger(root, cron) {
|
|
41
|
+
let none = { edit: null, note: null };
|
|
42
|
+
let existing = await triggerCrons(root);
|
|
43
|
+
if (existing.some((entry) => normalized(entry.cron) === normalized(cron)))
|
|
44
|
+
return none;
|
|
45
|
+
let file = await triggerFile(root);
|
|
46
|
+
if (file === null)
|
|
47
|
+
return none;
|
|
48
|
+
if (file.path !== CONFIG) {
|
|
49
|
+
return {
|
|
50
|
+
edit: null,
|
|
51
|
+
note: manualNote("Add", file.path, cron, `${file.path} configures the Worker`),
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
let missing = {
|
|
55
|
+
edit: null,
|
|
56
|
+
note: manualNote("Add", CONFIG, cron, `${CONFIG} has no worker.triggers list`),
|
|
57
|
+
};
|
|
58
|
+
let imported = ensureImport(CONFIG, file.source, { kind: "named", name: "triggers" }, (specifier) => specifier === "cf/config", "cf/config", "triggers");
|
|
59
|
+
if (isFailure(imported))
|
|
60
|
+
return missing;
|
|
61
|
+
let added = addElement(CONFIG, imported.data.source, {
|
|
62
|
+
call: "defineConfig",
|
|
63
|
+
path: ["worker", "triggers"],
|
|
64
|
+
value: `${imported.data.local}.scheduled({ schedule: ${literal(cron)} })`,
|
|
65
|
+
});
|
|
66
|
+
if (isFailure(added))
|
|
67
|
+
return missing;
|
|
68
|
+
return { edit: { path: CONFIG, before: file.source, after: added.data.source }, note: null };
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* The source range of each `triggers.scheduled({ schedule: … })` entry in `tokens` whose
|
|
72
|
+
* schedule is `cron`, widened over the JSDoc above it and one comma beside it.
|
|
73
|
+
*/
|
|
74
|
+
function scheduledEntries(source, tokens, cron) {
|
|
75
|
+
let ranges = [];
|
|
76
|
+
let code = tokens.filter((token) => token.type !== "comment");
|
|
77
|
+
let is = (token, value) => token?.value === value;
|
|
78
|
+
for (let index = 0; index < code.length; index += 1) {
|
|
79
|
+
let start = code[index];
|
|
80
|
+
if (start.type !== "identifier" || is(code[index - 1], "."))
|
|
81
|
+
continue;
|
|
82
|
+
if (!is(code[index + 1], ".") ||
|
|
83
|
+
!is(code[index + 2], "scheduled") ||
|
|
84
|
+
!is(code[index + 3], "(")) {
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
let depth = 0;
|
|
88
|
+
let close = index + 3;
|
|
89
|
+
for (; close < code.length; close += 1) {
|
|
90
|
+
let value = code[close]?.value;
|
|
91
|
+
if (value === "(" || value === "{" || value === "[")
|
|
92
|
+
depth += 1;
|
|
93
|
+
if (value === ")" || value === "}" || value === "]")
|
|
94
|
+
depth -= 1;
|
|
95
|
+
if (depth === 0)
|
|
96
|
+
break;
|
|
97
|
+
}
|
|
98
|
+
let inside = code.slice(index + 4, close);
|
|
99
|
+
let at = inside.findIndex((token, offset) => token.value === "schedule" && is(inside[offset + 1], ":"));
|
|
100
|
+
let schedule = at === -1 ? undefined : inside[at + 2];
|
|
101
|
+
if (schedule?.type !== "string")
|
|
102
|
+
continue;
|
|
103
|
+
if (normalized(schedule.value.slice(1, -1)) !== normalized(cron))
|
|
104
|
+
continue;
|
|
105
|
+
let from = start.start;
|
|
106
|
+
let to = code[close].end;
|
|
107
|
+
let comments = tokens.filter((token) => token.type === "comment" && token.end <= from);
|
|
108
|
+
for (let comment of comments.reverse()) {
|
|
109
|
+
if (source.slice(comment.end, from).trim() !== "")
|
|
110
|
+
break;
|
|
111
|
+
from = comment.start;
|
|
112
|
+
}
|
|
113
|
+
let after = code[close + 1];
|
|
114
|
+
let before = code[index - 1];
|
|
115
|
+
if (is(after, ","))
|
|
116
|
+
to =
|
|
117
|
+
after.end +
|
|
118
|
+
(/^[ \t]*/.exec(source.slice(after.end))?.[0].length ?? 0);
|
|
119
|
+
else if (is(before, ","))
|
|
120
|
+
from = Math.min(from, before.start);
|
|
121
|
+
ranges.push([from, to]);
|
|
122
|
+
index = close;
|
|
123
|
+
}
|
|
124
|
+
return ranges;
|
|
125
|
+
}
|
|
126
|
+
/** `source` without `[from, to)`, and without the line that range leaves empty. */
|
|
127
|
+
function cut(source, from, to) {
|
|
128
|
+
let lineStart = source.lastIndexOf("\n", from - 1) + 1;
|
|
129
|
+
let lineEnd = source.indexOf("\n", to);
|
|
130
|
+
let end = lineEnd === -1 ? source.length : lineEnd;
|
|
131
|
+
if (source.slice(lineStart, from).trim() === "" && source.slice(to, end).trim() === "") {
|
|
132
|
+
return source.slice(0, lineStart) + source.slice(Math.min(end + 1, source.length));
|
|
133
|
+
}
|
|
134
|
+
return source.slice(0, from) + source.slice(to);
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* `source`, the text of `cloudflare.config.ts`, without its scheduled triggers for `cron`, or
|
|
138
|
+
* `null` when it has none or does not scan.
|
|
139
|
+
*/
|
|
140
|
+
export function removeTrigger(source, cron) {
|
|
141
|
+
let tokens = tokenize(CONFIG, source);
|
|
142
|
+
if (isFailure(tokens))
|
|
143
|
+
return null;
|
|
144
|
+
let ranges = scheduledEntries(source, tokens.data, cron);
|
|
145
|
+
if (ranges.length === 0)
|
|
146
|
+
return null;
|
|
147
|
+
return ranges.reduceRight((text, [from, to]) => cut(text, from, to), source);
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* What unscheduling `cron` takes once no remaining job runs on it: the edit to
|
|
151
|
+
* `cloudflare.config.ts`, and a note for each other file whose trigger still delivers it.
|
|
152
|
+
*/
|
|
153
|
+
export async function planUntrigger(root, cron) {
|
|
154
|
+
let read = await wrap(() => readFile(join(root, CONFIG), "utf8"));
|
|
155
|
+
let source = isFailure(read) ? null : read.data;
|
|
156
|
+
let removed = source === null ? null : removeTrigger(source, cron);
|
|
157
|
+
let elsewhere = (await triggerCrons(root)).find((entry) => normalized(entry.cron) === normalized(cron) && (entry.file !== CONFIG || removed === null));
|
|
158
|
+
let note = elsewhere === undefined
|
|
159
|
+
? null
|
|
160
|
+
: manualNote("Remove", elsewhere.file, cron, "no other job runs on its schedule");
|
|
161
|
+
let edit = source === null || removed === null ? null : { path: CONFIG, before: source, after: removed };
|
|
162
|
+
return { edit, note };
|
|
163
|
+
}
|