@ubean/preset 0.1.2 → 0.1.4

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.
@@ -0,0 +1,342 @@
1
+ //#region src/capabilities.d.ts
2
+ type RuntimeTarget = 'node' | 'worker' | 'browser' | 'deno' | 'bun' | 'edge-light';
3
+ interface CapabilitySet {
4
+ staticServe: boolean;
5
+ websocket: boolean;
6
+ sse: boolean;
7
+ cronTriggers: boolean;
8
+ queues: boolean;
9
+ kv: boolean;
10
+ storage: boolean;
11
+ database: boolean;
12
+ envVars: boolean;
13
+ secrets: boolean;
14
+ nodeCompat: boolean;
15
+ streaming: boolean;
16
+ compression: boolean;
17
+ https: boolean;
18
+ http2: boolean;
19
+ middleware: boolean;
20
+ bodyLimit: boolean;
21
+ multipart: boolean;
22
+ rpc: boolean;
23
+ }
24
+ interface CapabilityInfo extends CapabilitySet {
25
+ runtime: RuntimeTarget[];
26
+ }
27
+ type CapabilityName = keyof CapabilitySet;
28
+ interface CapabilityRequirement {
29
+ capability: CapabilityName;
30
+ required: boolean;
31
+ message?: string;
32
+ }
33
+ interface CapabilityDiagnostic {
34
+ capability: CapabilityName;
35
+ supported: boolean;
36
+ required: boolean;
37
+ message: string;
38
+ }
39
+ interface CapabilityDiagnosisResult {
40
+ valid: boolean;
41
+ diagnostics: CapabilityDiagnostic[];
42
+ errors: string[];
43
+ warnings: string[];
44
+ presetName: string;
45
+ }
46
+ declare function createCapabilitySet(overrides?: Partial<CapabilitySet>): CapabilitySet;
47
+ declare function diagnoseCapabilities(presetName: string, presetCapabilities: Partial<CapabilitySet>, requirements: CapabilityRequirement[]): CapabilityDiagnosisResult;
48
+ declare function requireCapability(capability: CapabilityName, required?: boolean, message?: string): CapabilityRequirement;
49
+ declare const NODE_CAPABILITIES: CapabilitySet;
50
+ declare const STANDARD_CAPABILITIES: CapabilitySet;
51
+ declare const WORKER_CAPABILITIES: CapabilitySet;
52
+ declare const DEV_REQUIREMENTS: CapabilityRequirement[];
53
+ declare const NODE_REQUIREMENTS: CapabilityRequirement[];
54
+ //#endregion
55
+ //#region src/registry.d.ts
56
+ type PresetHooks = {
57
+ 'build:before'?: (ctx: PresetBuildContext) => void | Promise<void>;
58
+ 'build:after'?: (ctx: PresetBuildContext) => void | Promise<void>;
59
+ compiled?: (ctx: PresetBuildContext) => void | Promise<void>;
60
+ 'dev:setup'?: (ctx: PresetDevContext) => void | Promise<void>;
61
+ };
62
+ interface PresetBuildContext {
63
+ cwd: string;
64
+ outputDir: string;
65
+ preset: ResolvedPreset;
66
+ config: Record<string, unknown>;
67
+ }
68
+ interface PresetDevContext {
69
+ cwd: string;
70
+ preset: ResolvedPreset;
71
+ config: Record<string, unknown>;
72
+ }
73
+ interface PresetOutputConfig {
74
+ dir?: string;
75
+ serverDir?: string;
76
+ publicDir?: string;
77
+ }
78
+ interface PresetRollupConfig {
79
+ plugins?: unknown[];
80
+ output?: Record<string, unknown>;
81
+ external?: string[];
82
+ }
83
+ interface PresetMeta {
84
+ name: string;
85
+ aliases?: string[];
86
+ stdName?: string;
87
+ static?: boolean;
88
+ dev?: boolean;
89
+ compatibilityDate?: string;
90
+ url?: string;
91
+ }
92
+ interface PresetRuntimeConfig {
93
+ entry?: string;
94
+ handler?: string;
95
+ compatibilityDate?: string;
96
+ compatibilityFlags?: string[];
97
+ [key: string]: unknown;
98
+ }
99
+ interface PresetDefinition {
100
+ name?: string;
101
+ extends?: string;
102
+ entry?: string;
103
+ exportConditions?: string[];
104
+ serve?: {
105
+ host?: string;
106
+ port?: number;
107
+ };
108
+ build?: {
109
+ outputDir?: string;
110
+ format?: 'esm' | 'cjs';
111
+ externals?: string[];
112
+ minify?: boolean;
113
+ rollupConfig?: PresetRollupConfig;
114
+ };
115
+ output?: PresetOutputConfig;
116
+ runtime?: PresetRuntimeConfig;
117
+ devServer?: {
118
+ runner?: string;
119
+ };
120
+ capabilities?: Partial<CapabilitySet>;
121
+ capabilityInfo?: Partial<CapabilityInfo>;
122
+ hooks?: PresetHooks;
123
+ alias?: Record<string, string>;
124
+ wasm?: {
125
+ lazy?: boolean;
126
+ esmImport?: boolean;
127
+ };
128
+ unenv?: unknown[];
129
+ commands?: {
130
+ preview?: string;
131
+ deploy?: string;
132
+ };
133
+ nitro?: Record<string, unknown>;
134
+ }
135
+ type Preset = PresetDefinition | (() => PresetDefinition);
136
+ interface ResolvedPreset extends PresetDefinition {
137
+ name: string;
138
+ _meta: PresetMeta;
139
+ }
140
+ declare function definePreset<P extends PresetDefinition>(preset: P, meta?: PresetMeta): P & {
141
+ _meta: PresetMeta;
142
+ name: string;
143
+ };
144
+ declare function resolvePreset(name: string): ResolvedPreset | undefined;
145
+ declare function getRegisteredPresets(): Array<PresetDefinition & {
146
+ _meta: PresetMeta;
147
+ }>;
148
+ declare function registerPreset(preset: Preset, meta?: PresetMeta): void;
149
+ declare function getPresetNames(): string[];
150
+ declare function getPresetAliases(): Map<string, string>;
151
+ //#endregion
152
+ //#region src/cloudflare.d.ts
153
+ declare const cloudflarePreset: {
154
+ capabilities: CapabilitySet;
155
+ entry: string;
156
+ exportConditions: string[];
157
+ build: {
158
+ outputDir: string;
159
+ format: "esm";
160
+ minify: false;
161
+ externals: string[];
162
+ rollupConfig: {
163
+ external: string[];
164
+ };
165
+ };
166
+ output: {
167
+ dir: string;
168
+ serverDir: string;
169
+ publicDir: string;
170
+ };
171
+ runtime: {
172
+ entry: string;
173
+ handler: string;
174
+ compatibilityDate: string;
175
+ compatibilityFlags: string[];
176
+ };
177
+ wasm: {
178
+ lazy: false;
179
+ esmImport: true;
180
+ };
181
+ serve: {
182
+ host: string;
183
+ port: number;
184
+ };
185
+ commands: {
186
+ preview: string;
187
+ deploy: string;
188
+ };
189
+ hooks: {
190
+ 'build:before': () => Promise<void>;
191
+ compiled: () => Promise<void>;
192
+ };
193
+ } & {
194
+ _meta: PresetMeta;
195
+ name: string;
196
+ };
197
+ declare const cloudflareDevPreset: {
198
+ extends: string;
199
+ devServer: {
200
+ runner: string;
201
+ };
202
+ } & {
203
+ _meta: PresetMeta;
204
+ name: string;
205
+ };
206
+ interface WranglerConfig {
207
+ name?: string;
208
+ main?: string;
209
+ compatibility_date?: string;
210
+ compatibility_flags?: string[];
211
+ workers_dev?: boolean;
212
+ routes?: string[];
213
+ kv_namespaces?: Array<{
214
+ binding: string;
215
+ id?: string;
216
+ preview_id?: string;
217
+ }>;
218
+ vars?: Record<string, string>;
219
+ secrets?: string[];
220
+ queues?: {
221
+ producers?: Array<{
222
+ binding: string;
223
+ queue: string;
224
+ }>;
225
+ consumers?: Array<{
226
+ queue: string;
227
+ }>;
228
+ };
229
+ d1_databases?: Array<{
230
+ binding: string;
231
+ database_id?: string;
232
+ preview_database_id?: string;
233
+ }>;
234
+ r2_buckets?: Array<{
235
+ binding: string;
236
+ bucket_name?: string;
237
+ preview_bucket_name?: string;
238
+ }>;
239
+ observability?: {
240
+ enabled: boolean;
241
+ };
242
+ assets?: {
243
+ directory?: string;
244
+ binding?: string;
245
+ };
246
+ }
247
+ declare function generateWranglerConfig(options: {
248
+ name: string;
249
+ entry?: string;
250
+ compatibilityDate?: string;
251
+ compatibilityFlags?: string[];
252
+ kvNamespaces?: Array<{
253
+ binding: string;
254
+ id?: string;
255
+ }>;
256
+ vars?: Record<string, string>;
257
+ d1Databases?: Array<{
258
+ binding: string;
259
+ databaseId?: string;
260
+ }>;
261
+ r2Buckets?: Array<{
262
+ binding: string;
263
+ bucketName?: string;
264
+ }>;
265
+ queuesProducers?: Array<{
266
+ binding: string;
267
+ queue: string;
268
+ }>;
269
+ queuesConsumers?: Array<{
270
+ queue: string;
271
+ }>;
272
+ assetsDir?: string;
273
+ observability?: boolean;
274
+ }): WranglerConfig;
275
+ declare function serializeWranglerToml(config: WranglerConfig): string;
276
+ //#endregion
277
+ //#region src/node.d.ts
278
+ declare const nodePreset: {
279
+ extends: string;
280
+ capabilities: CapabilitySet;
281
+ build: {
282
+ outputDir: string;
283
+ format: "esm";
284
+ externals: string[];
285
+ };
286
+ runtime: {
287
+ entry: string;
288
+ handler: string;
289
+ };
290
+ serve: {
291
+ host: string;
292
+ port: number;
293
+ };
294
+ commands: {
295
+ preview: string;
296
+ };
297
+ } & {
298
+ _meta: PresetMeta;
299
+ name: string;
300
+ };
301
+ //#endregion
302
+ //#region src/standard.d.ts
303
+ declare const standardPreset: {
304
+ capabilities: CapabilitySet;
305
+ build: {
306
+ outputDir: string;
307
+ format: "esm";
308
+ externals: string[];
309
+ };
310
+ runtime: {
311
+ entry: string;
312
+ };
313
+ serve: {
314
+ host: string;
315
+ port: number;
316
+ };
317
+ } & {
318
+ _meta: PresetMeta;
319
+ name: string;
320
+ };
321
+ //#endregion
322
+ //#region src/detect.d.ts
323
+ interface PresetDetectionHints {
324
+ cwd?: string;
325
+ explicitPreset?: string;
326
+ environment?: Record<string, string | undefined>;
327
+ globalThis?: Record<string, unknown>;
328
+ }
329
+ interface PresetDetectionResult {
330
+ preset: ResolvedPreset;
331
+ source: 'explicit' | 'config-file' | 'environment' | 'default';
332
+ reason?: string;
333
+ }
334
+ declare function detectPreset(hints?: PresetDetectionHints): PresetDetectionResult;
335
+ declare function resolvePresetWithDetection(explicitPreset?: string, cwd?: string): PresetDetectionResult;
336
+ declare function listDetectablePresets(): PresetDefinition[];
337
+ //#endregion
338
+ //#region src/index.d.ts
339
+ declare function registerBuiltinPresets(): void;
340
+ declare function resolvePresetByName(name: string): ResolvedPreset;
341
+ //#endregion
342
+ export { CapabilityDiagnosisResult, CapabilityDiagnostic, CapabilityInfo, CapabilityName, CapabilityRequirement, CapabilitySet, DEV_REQUIREMENTS, NODE_CAPABILITIES, NODE_REQUIREMENTS, type Preset, type PresetBuildContext, type PresetDefinition, type PresetDetectionHints, type PresetDetectionResult, type PresetDevContext, type PresetHooks, type PresetMeta, type ResolvedPreset, RuntimeTarget, STANDARD_CAPABILITIES, WORKER_CAPABILITIES, type WranglerConfig, cloudflareDevPreset, cloudflarePreset, createCapabilitySet, definePreset, detectPreset, diagnoseCapabilities, generateWranglerConfig, getPresetAliases, getPresetNames, getRegisteredPresets, listDetectablePresets, nodePreset, registerBuiltinPresets, registerPreset, requireCapability, resolvePreset, resolvePresetByName, resolvePresetWithDetection, serializeWranglerToml, standardPreset };
package/dist/index.js ADDED
@@ -0,0 +1,650 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ //#region src/capabilities.ts
4
+ const DEFAULT_CAPABILITIES = {
5
+ staticServe: false,
6
+ websocket: false,
7
+ sse: false,
8
+ cronTriggers: false,
9
+ queues: false,
10
+ kv: false,
11
+ storage: false,
12
+ database: false,
13
+ envVars: true,
14
+ secrets: false,
15
+ nodeCompat: false,
16
+ streaming: true,
17
+ compression: false,
18
+ https: false,
19
+ http2: false,
20
+ middleware: true,
21
+ bodyLimit: true,
22
+ multipart: false,
23
+ rpc: false
24
+ };
25
+ function createCapabilitySet(overrides = {}) {
26
+ return {
27
+ ...DEFAULT_CAPABILITIES,
28
+ ...overrides
29
+ };
30
+ }
31
+ const CAPABILITY_MESSAGES = {
32
+ staticServe: { missing: "Preset does not support static file serving" },
33
+ websocket: { missing: "Preset does not support WebSocket" },
34
+ sse: { missing: "Preset does not support Server-Sent Events" },
35
+ cronTriggers: { missing: "Preset does not support cron triggers" },
36
+ queues: { missing: "Preset does not support queue processing" },
37
+ kv: { missing: "Preset does not support KV storage" },
38
+ storage: { missing: "Preset does not support blob storage" },
39
+ database: { missing: "Preset does not have built-in database support" },
40
+ envVars: { missing: "Preset does not support environment variables" },
41
+ secrets: { missing: "Preset does not support secret management" },
42
+ nodeCompat: { missing: "Preset does not provide Node.js compatibility layer" },
43
+ streaming: { missing: "Preset does not support streaming responses" },
44
+ compression: { missing: "Preset does not support response compression" },
45
+ https: { missing: "Preset does not support HTTPS" },
46
+ http2: { missing: "Preset does not support HTTP/2" },
47
+ middleware: { missing: "Preset does not support middleware" },
48
+ bodyLimit: { missing: "Preset does not support request body size limits" },
49
+ multipart: { missing: "Preset does not support multipart/form-data" },
50
+ rpc: { missing: "Preset does not support RPC transport" }
51
+ };
52
+ function diagnoseCapabilities(presetName, presetCapabilities, requirements) {
53
+ const capabilities = createCapabilitySet(presetCapabilities);
54
+ const diagnostics = [];
55
+ const errors = [];
56
+ const warnings = [];
57
+ for (const req of requirements) {
58
+ const supported = capabilities[req.capability];
59
+ const messages = CAPABILITY_MESSAGES[req.capability];
60
+ const message = req.message || messages.missing;
61
+ diagnostics.push({
62
+ capability: req.capability,
63
+ supported,
64
+ required: req.required,
65
+ message: supported ? `${req.capability} is supported` : message
66
+ });
67
+ if (!supported) if (req.required) errors.push(`[${presetName}] ${message}`);
68
+ else warnings.push(`[${presetName}] ${message}`);
69
+ }
70
+ return {
71
+ valid: errors.length === 0,
72
+ diagnostics,
73
+ errors,
74
+ warnings,
75
+ presetName
76
+ };
77
+ }
78
+ function requireCapability(capability, required = true, message) {
79
+ return {
80
+ capability,
81
+ required,
82
+ message
83
+ };
84
+ }
85
+ const NODE_CAPABILITIES = createCapabilitySet({
86
+ staticServe: true,
87
+ websocket: true,
88
+ sse: true,
89
+ cronTriggers: true,
90
+ queues: true,
91
+ kv: true,
92
+ storage: true,
93
+ database: true,
94
+ secrets: true,
95
+ nodeCompat: true,
96
+ streaming: true,
97
+ compression: true,
98
+ https: true,
99
+ http2: true,
100
+ multipart: true,
101
+ rpc: true
102
+ });
103
+ const STANDARD_CAPABILITIES = createCapabilitySet({
104
+ staticServe: true,
105
+ sse: true,
106
+ middleware: true,
107
+ bodyLimit: true,
108
+ streaming: true
109
+ });
110
+ const WORKER_CAPABILITIES = createCapabilitySet({
111
+ staticServe: true,
112
+ websocket: true,
113
+ sse: true,
114
+ kv: true,
115
+ storage: false,
116
+ envVars: true,
117
+ nodeCompat: false,
118
+ streaming: true,
119
+ middleware: true,
120
+ bodyLimit: true
121
+ });
122
+ const DEV_REQUIREMENTS = [
123
+ requireCapability("middleware", true, "Dev server requires middleware support"),
124
+ requireCapability("streaming", true, "Dev server requires streaming support for SSE/HMR"),
125
+ requireCapability("envVars", true, "Dev server requires environment variable support"),
126
+ requireCapability("staticServe", false, "Static file serving is recommended for dev"),
127
+ requireCapability("nodeCompat", false, "Node compatibility enables full dev feature set")
128
+ ];
129
+ const NODE_REQUIREMENTS = DEV_REQUIREMENTS;
130
+ //#endregion
131
+ //#region src/registry.ts
132
+ const presets = /* @__PURE__ */ new Map();
133
+ const presetNames = /* @__PURE__ */ new Map();
134
+ function definePreset(preset, meta) {
135
+ const name = meta?.name || preset.name || "unknown";
136
+ const finalMeta = {
137
+ name,
138
+ aliases: [],
139
+ static: false,
140
+ dev: false,
141
+ ...meta
142
+ };
143
+ const presetWithMeta = {
144
+ ...preset,
145
+ name,
146
+ _meta: finalMeta
147
+ };
148
+ presets.set(name, presetWithMeta);
149
+ presetNames.set(name, name);
150
+ if (finalMeta.aliases) for (const alias of finalMeta.aliases) presetNames.set(alias, name);
151
+ return presetWithMeta;
152
+ }
153
+ function resolvePresetDefinition(preset) {
154
+ return typeof preset === "function" ? preset() : preset;
155
+ }
156
+ function resolvePreset(name) {
157
+ const resolvedName = presetNames.get(name);
158
+ if (!resolvedName) return void 0;
159
+ if (!presets.get(resolvedName)) return void 0;
160
+ return resolvePresetWithInheritance(resolvedName, /* @__PURE__ */ new Set());
161
+ }
162
+ function resolvePresetWithInheritance(name, visited) {
163
+ if (visited.has(name)) throw new Error(`Circular preset inheritance detected: ${[...visited, name].join(" -> ")}`);
164
+ visited.add(name);
165
+ const preset = presets.get(name);
166
+ if (!preset) return void 0;
167
+ let base = { name };
168
+ if (preset.extends) {
169
+ const parent = resolvePresetWithInheritance(preset.extends, visited);
170
+ if (parent) base = mergePreset(parent, {});
171
+ }
172
+ const resolved = mergePreset(base, preset);
173
+ resolved.name = name;
174
+ resolved._meta = preset._meta;
175
+ return resolved;
176
+ }
177
+ function mergePreset(base, override) {
178
+ return {
179
+ name: override.name ?? base.name,
180
+ extends: override.extends ?? base.extends,
181
+ entry: override.entry ?? base.entry,
182
+ exportConditions: override.exportConditions ?? base.exportConditions,
183
+ serve: {
184
+ ...base.serve,
185
+ ...override.serve
186
+ },
187
+ build: {
188
+ ...base.build,
189
+ ...override.build
190
+ },
191
+ output: {
192
+ ...base.output,
193
+ ...override.output
194
+ },
195
+ runtime: {
196
+ ...base.runtime,
197
+ ...override.runtime
198
+ },
199
+ devServer: {
200
+ ...base.devServer,
201
+ ...override.devServer
202
+ },
203
+ capabilities: {
204
+ ...base.capabilities,
205
+ ...override.capabilities
206
+ },
207
+ capabilityInfo: {
208
+ ...base.capabilityInfo,
209
+ ...override.capabilityInfo
210
+ },
211
+ hooks: {
212
+ ...base.hooks,
213
+ ...override.hooks
214
+ },
215
+ alias: {
216
+ ...base.alias,
217
+ ...override.alias
218
+ },
219
+ wasm: {
220
+ ...base.wasm,
221
+ ...override.wasm
222
+ },
223
+ unenv: [...base.unenv || [], ...override.unenv || []],
224
+ commands: {
225
+ ...base.commands,
226
+ ...override.commands
227
+ },
228
+ nitro: {
229
+ ...base.nitro,
230
+ ...override.nitro
231
+ }
232
+ };
233
+ }
234
+ function getRegisteredPresets() {
235
+ return [...presets.values()];
236
+ }
237
+ function registerPreset(preset, meta) {
238
+ definePreset(resolvePresetDefinition(preset), meta);
239
+ }
240
+ function getPresetNames() {
241
+ return [...presets.keys()];
242
+ }
243
+ function getPresetAliases() {
244
+ return new Map(presetNames);
245
+ }
246
+ const cloudflarePreset = definePreset({
247
+ capabilities: createCapabilitySet({
248
+ staticServe: true,
249
+ websocket: true,
250
+ sse: true,
251
+ cronTriggers: true,
252
+ queues: true,
253
+ kv: true,
254
+ storage: true,
255
+ database: true,
256
+ envVars: true,
257
+ secrets: true,
258
+ nodeCompat: false,
259
+ streaming: true,
260
+ compression: false,
261
+ https: true,
262
+ http2: false,
263
+ middleware: true,
264
+ bodyLimit: true,
265
+ multipart: true,
266
+ rpc: false
267
+ }),
268
+ entry: "worker",
269
+ exportConditions: ["workerd", "worker"],
270
+ build: {
271
+ outputDir: "dist/cloudflare",
272
+ format: "esm",
273
+ minify: false,
274
+ externals: [
275
+ "hono",
276
+ "c12",
277
+ "citty",
278
+ "consola",
279
+ "defu",
280
+ "hookable",
281
+ "pathe",
282
+ "ufo",
283
+ "zod",
284
+ "cloudflare:workers"
285
+ ],
286
+ rollupConfig: { external: ["cloudflare:*", "node:*"] }
287
+ },
288
+ output: {
289
+ dir: "dist/cloudflare",
290
+ serverDir: "dist/cloudflare",
291
+ publicDir: "dist/cloudflare/public"
292
+ },
293
+ runtime: {
294
+ entry: "worker/index.mjs",
295
+ handler: "fetch",
296
+ compatibilityDate: "2024-09-01",
297
+ compatibilityFlags: ["nodejs_compat"]
298
+ },
299
+ wasm: {
300
+ lazy: false,
301
+ esmImport: true
302
+ },
303
+ serve: {
304
+ host: "localhost",
305
+ port: 8787
306
+ },
307
+ commands: {
308
+ preview: "npx wrangler dev",
309
+ deploy: "npx wrangler deploy"
310
+ },
311
+ hooks: {
312
+ "build:before": async () => {},
313
+ compiled: async () => {}
314
+ }
315
+ }, {
316
+ name: "cloudflare",
317
+ aliases: [
318
+ "cloudflare-pages",
319
+ "cloudflare-module",
320
+ "cf",
321
+ "wrangler",
322
+ "workers"
323
+ ],
324
+ stdName: "cloudflare_workers",
325
+ dev: true,
326
+ compatibilityDate: "2024-09-01"
327
+ });
328
+ const cloudflareDevPreset = definePreset({
329
+ extends: "cloudflare",
330
+ devServer: { runner: "miniflare" }
331
+ }, {
332
+ name: "cloudflare-dev",
333
+ aliases: ["cf-dev", "wrangler-dev"],
334
+ dev: true
335
+ });
336
+ function generateWranglerConfig(options) {
337
+ const config = {
338
+ name: options.name,
339
+ main: options.entry || "dist/cloudflare/worker/index.mjs",
340
+ compatibility_date: options.compatibilityDate || "2024-09-01",
341
+ compatibility_flags: options.compatibilityFlags || ["nodejs_compat"],
342
+ workers_dev: true,
343
+ observability: { enabled: options.observability ?? true }
344
+ };
345
+ if (options.kvNamespaces && options.kvNamespaces.length > 0) config.kv_namespaces = options.kvNamespaces.map((ns) => ({
346
+ binding: ns.binding,
347
+ id: ns.id
348
+ }));
349
+ if (options.vars && Object.keys(options.vars).length > 0) config.vars = options.vars;
350
+ if (options.d1Databases && options.d1Databases.length > 0) config.d1_databases = options.d1Databases.map((db) => ({
351
+ binding: db.binding,
352
+ database_id: db.databaseId
353
+ }));
354
+ if (options.r2Buckets && options.r2Buckets.length > 0) config.r2_buckets = options.r2Buckets.map((b) => ({
355
+ binding: b.binding,
356
+ bucket_name: b.bucketName
357
+ }));
358
+ if (options.queuesProducers && options.queuesProducers.length > 0) config.queues = {
359
+ ...config.queues,
360
+ producers: options.queuesProducers
361
+ };
362
+ if (options.queuesConsumers && options.queuesConsumers.length > 0) config.queues = {
363
+ ...config.queues,
364
+ consumers: options.queuesConsumers
365
+ };
366
+ if (options.assetsDir) config.assets = {
367
+ directory: options.assetsDir,
368
+ binding: "ASSETS"
369
+ };
370
+ return config;
371
+ }
372
+ function serializeWranglerToml(config) {
373
+ const lines = [];
374
+ const indent = "";
375
+ function push(key, value, prefix = "") {
376
+ if (value === void 0 || value === null) return;
377
+ if (typeof value === "string") lines.push(`${prefix}${key} = "${escapeToml(value)}"`);
378
+ else if (typeof value === "boolean") lines.push(`${prefix}${key} = ${value}`);
379
+ else if (typeof value === "number") lines.push(`${prefix}${key} = ${value}`);
380
+ else if (Array.isArray(value)) {
381
+ if (value.length === 0) return;
382
+ if (typeof value[0] === "string") {
383
+ const items = value.map((v) => `"${escapeToml(String(v))}"`).join(", ");
384
+ lines.push(`${prefix}${key} = [${items}]`);
385
+ } else {
386
+ lines.push(`${prefix}[[${key}]]`);
387
+ for (const item of value) lines.push(`${prefix} { ${Object.entries(item).filter(([, v]) => v !== void 0 && v !== null).map(([k, v]) => {
388
+ if (typeof v === "string") return `${k} = "${escapeToml(v)}"`;
389
+ if (typeof v === "boolean") return `${k} = ${v}`;
390
+ return `${k} = ${v}`;
391
+ }).join(", ")} }`);
392
+ }
393
+ } else if (typeof value === "object") {
394
+ const entries = Object.entries(value).filter(([, v]) => v !== void 0 && v !== null);
395
+ if (entries.length === 0) return;
396
+ lines.push(`${prefix}[${key}]`);
397
+ for (const [k, v] of entries) if (Array.isArray(v) && typeof v[0] !== "string" && v.length > 0) {
398
+ lines.push(`${prefix}[[${key}.${k}]]`);
399
+ for (const item of v) {
400
+ const itemEntries = Object.entries(item).filter(([, iv]) => iv !== void 0 && iv !== null);
401
+ lines.push(itemEntries.map(([ik, iv]) => {
402
+ if (typeof iv === "string") return `${prefix} ${ik} = "${escapeToml(iv)}"`;
403
+ return `${prefix} ${ik} = ${iv}`;
404
+ }).join("\n"));
405
+ }
406
+ } else if (typeof v === "string") lines.push(`${prefix}${k} = "${escapeToml(v)}"`);
407
+ else if (typeof v === "boolean") lines.push(`${prefix}${k} = ${v}`);
408
+ else if (typeof v === "number") lines.push(`${prefix}${k} = ${v}`);
409
+ }
410
+ }
411
+ push("name", config.name);
412
+ push("main", config.main);
413
+ push("compatibility_date", config.compatibility_date);
414
+ push("compatibility_flags", config.compatibility_flags);
415
+ push("workers_dev", config.workers_dev);
416
+ if (config.routes && config.routes.length > 0) push("routes", config.routes);
417
+ if (config.assets) push("assets", config.assets);
418
+ if (config.observability) push("observability", config.observability);
419
+ if (config.kv_namespaces && config.kv_namespaces.length > 0) for (const ns of config.kv_namespaces) {
420
+ const nsLines = [`${indent}[[kv_namespaces]]`];
421
+ if (ns.binding) nsLines.push(`${indent}binding = "${escapeToml(ns.binding)}"`);
422
+ if (ns.id) nsLines.push(`${indent}id = "${escapeToml(ns.id)}"`);
423
+ if (ns.preview_id) nsLines.push(`${indent}preview_id = "${escapeToml(ns.preview_id)}"`);
424
+ lines.push(nsLines.join("\n"));
425
+ }
426
+ if (config.vars && Object.keys(config.vars).length > 0) {
427
+ lines.push(`${indent}[vars]`);
428
+ for (const [k, v] of Object.entries(config.vars)) lines.push(`${indent}${k} = "${escapeToml(v)}"`);
429
+ }
430
+ if (config.d1_databases && config.d1_databases.length > 0) for (const db of config.d1_databases) {
431
+ const dbLines = [`${indent}[[d1_databases]]`];
432
+ if (db.binding) dbLines.push(`${indent}binding = "${escapeToml(db.binding)}"`);
433
+ if (db.database_id) dbLines.push(`${indent}database_id = "${escapeToml(db.database_id)}"`);
434
+ if (db.preview_database_id) dbLines.push(`${indent}preview_database_id = "${escapeToml(db.preview_database_id)}"`);
435
+ lines.push(dbLines.join("\n"));
436
+ }
437
+ if (config.r2_buckets && config.r2_buckets.length > 0) for (const b of config.r2_buckets) {
438
+ const bLines = [`${indent}[[r2_buckets]]`];
439
+ if (b.binding) bLines.push(`${indent}binding = "${escapeToml(b.binding)}"`);
440
+ if (b.bucket_name) bLines.push(`${indent}bucket_name = "${escapeToml(b.bucket_name)}"`);
441
+ if (b.preview_bucket_name) bLines.push(`${indent}preview_bucket_name = "${escapeToml(b.preview_bucket_name)}"`);
442
+ lines.push(bLines.join("\n"));
443
+ }
444
+ if (config.queues) {
445
+ if (config.queues.producers && config.queues.producers.length > 0) for (const p of config.queues.producers) {
446
+ const pLines = [`${indent}[[queues.producers]]`];
447
+ if (p.binding) pLines.push(`${indent}binding = "${escapeToml(p.binding)}"`);
448
+ if (p.queue) pLines.push(`${indent}queue = "${escapeToml(p.queue)}"`);
449
+ lines.push(pLines.join("\n"));
450
+ }
451
+ if (config.queues.consumers && config.queues.consumers.length > 0) for (const c of config.queues.consumers) {
452
+ const cLines = [`${indent}[[queues.consumers]]`];
453
+ if (c.queue) cLines.push(`${indent}queue = "${escapeToml(c.queue)}"`);
454
+ lines.push(cLines.join("\n"));
455
+ }
456
+ }
457
+ return `${lines.join("\n")}\n`;
458
+ }
459
+ function escapeToml(str) {
460
+ return str.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
461
+ }
462
+ //#endregion
463
+ //#region src/node.ts
464
+ const nodePreset = definePreset({
465
+ extends: "standard",
466
+ capabilities: NODE_CAPABILITIES,
467
+ build: {
468
+ outputDir: "dist",
469
+ format: "esm",
470
+ externals: [
471
+ "hono",
472
+ "c12",
473
+ "citty",
474
+ "consola",
475
+ "defu",
476
+ "hookable",
477
+ "pathe",
478
+ "ufo",
479
+ "zod",
480
+ "mlly",
481
+ "rou3",
482
+ "scule",
483
+ "tinyglobby",
484
+ "ofetch",
485
+ "@standard-schema/spec"
486
+ ]
487
+ },
488
+ runtime: {
489
+ entry: "server/index.mjs",
490
+ handler: "handler"
491
+ },
492
+ serve: {
493
+ host: "localhost",
494
+ port: 9527
495
+ },
496
+ commands: { preview: "node dist/server/server.mjs" }
497
+ }, {
498
+ name: "node",
499
+ aliases: ["node-server", "nodedev"],
500
+ stdName: "node",
501
+ dev: true,
502
+ compatibilityDate: "2024-09-01"
503
+ });
504
+ //#endregion
505
+ //#region src/standard.ts
506
+ const standardPreset = definePreset({
507
+ capabilities: STANDARD_CAPABILITIES,
508
+ build: {
509
+ outputDir: "dist",
510
+ format: "esm",
511
+ externals: [
512
+ "hono",
513
+ "c12",
514
+ "citty",
515
+ "consola",
516
+ "defu",
517
+ "hookable",
518
+ "pathe",
519
+ "ufo",
520
+ "zod"
521
+ ]
522
+ },
523
+ runtime: { entry: "server" },
524
+ serve: {
525
+ host: "localhost",
526
+ port: 9527
527
+ }
528
+ }, {
529
+ name: "standard",
530
+ aliases: ["default"],
531
+ static: false,
532
+ dev: true
533
+ });
534
+ //#endregion
535
+ //#region src/detect.ts
536
+ function getPresetDef(preset) {
537
+ return typeof preset === "function" ? preset() : preset;
538
+ }
539
+ function detectByConfigFiles(cwd) {
540
+ if (existsSync(join(cwd, "wrangler.toml")) || existsSync(join(cwd, "wrangler.json"))) return "cloudflare";
541
+ if (existsSync(join(cwd, "package.json"))) try {
542
+ const pkg = JSON.parse(readFileSync(join(cwd, "package.json"), "utf-8"));
543
+ const deps = {
544
+ ...pkg.dependencies,
545
+ ...pkg.devDependencies
546
+ };
547
+ if ("wrangler" in deps || "@cloudflare/workers-types" in deps) return "cloudflare";
548
+ } catch {}
549
+ return null;
550
+ }
551
+ function detectByEnvironment(env, g) {
552
+ if (env.CF_WORKERS || env.WRANGLER || env.CLOUDFLARE_WORKER) return "cloudflare";
553
+ if (env.NODE_ENV === void 0 && "process" in g) return "node";
554
+ const gRecord = g;
555
+ if (gRecord.CacheStorage !== void 0 && gRecord.Deno === void 0 && gRecord.process === void 0) return "cloudflare";
556
+ if (gRecord.process !== void 0) {
557
+ if (gRecord.process.versions?.node) return "node";
558
+ }
559
+ return null;
560
+ }
561
+ function resolvePresetByNameSafe(name) {
562
+ return resolvePreset(getPresetAliases().get(name) || name) || null;
563
+ }
564
+ function detectPreset(hints = {}) {
565
+ const cwd = hints.cwd || process.cwd();
566
+ const env = hints.environment || (typeof process !== "undefined" ? process.env : {});
567
+ const g = hints.globalThis || (typeof globalThis !== "undefined" ? globalThis : {});
568
+ if (hints.explicitPreset) {
569
+ const explicit = resolvePresetByNameSafe(hints.explicitPreset);
570
+ if (explicit) return {
571
+ preset: explicit,
572
+ source: "explicit",
573
+ reason: `explicitly set to "${hints.explicitPreset}"`
574
+ };
575
+ }
576
+ const configDetected = detectByConfigFiles(cwd);
577
+ if (configDetected) {
578
+ const preset = resolvePresetByNameSafe(configDetected);
579
+ if (preset) return {
580
+ preset,
581
+ source: "config-file",
582
+ reason: configDetected === "cloudflare" ? "detected wrangler.toml or Cloudflare dependencies" : `detected ${configDetected} configuration`
583
+ };
584
+ }
585
+ const envDetected = detectByEnvironment(env, g);
586
+ if (envDetected) {
587
+ const preset = resolvePresetByNameSafe(envDetected);
588
+ if (preset) return {
589
+ preset,
590
+ source: "environment",
591
+ reason: `detected ${envDetected} runtime environment`
592
+ };
593
+ }
594
+ return {
595
+ preset: resolvePresetByNameSafe("standard"),
596
+ source: "default",
597
+ reason: "no specific platform detected, using standard preset"
598
+ };
599
+ }
600
+ function resolvePresetWithDetection(explicitPreset, cwd) {
601
+ return detectPreset({
602
+ explicitPreset,
603
+ cwd
604
+ });
605
+ }
606
+ function listDetectablePresets() {
607
+ return [
608
+ getPresetDef(standardPreset),
609
+ getPresetDef(nodePreset),
610
+ getPresetDef(cloudflarePreset),
611
+ getPresetDef(cloudflareDevPreset)
612
+ ];
613
+ }
614
+ //#endregion
615
+ //#region src/index.ts
616
+ const builtinPresets = [
617
+ standardPreset,
618
+ nodePreset,
619
+ cloudflarePreset,
620
+ cloudflareDevPreset
621
+ ];
622
+ function registerBuiltinPresets() {
623
+ for (const preset of builtinPresets) registerPreset(preset);
624
+ }
625
+ registerBuiltinPresets();
626
+ function resolvePresetByName(name) {
627
+ const preset = resolvePreset(getPresetAliases().get(name) || name);
628
+ if (preset) return preset;
629
+ const standardResolved = resolvePreset("standard");
630
+ if (standardResolved) return standardResolved;
631
+ return {
632
+ name: "standard",
633
+ _meta: { name: "standard" },
634
+ serve: {
635
+ host: "localhost",
636
+ port: 9527
637
+ },
638
+ build: {
639
+ outputDir: "dist",
640
+ format: "esm",
641
+ externals: []
642
+ },
643
+ runtime: { entry: "server" },
644
+ capabilities: {},
645
+ hooks: {},
646
+ commands: {}
647
+ };
648
+ }
649
+ //#endregion
650
+ export { DEV_REQUIREMENTS, NODE_CAPABILITIES, NODE_REQUIREMENTS, STANDARD_CAPABILITIES, WORKER_CAPABILITIES, cloudflareDevPreset, cloudflarePreset, createCapabilitySet, definePreset, detectPreset, diagnoseCapabilities, generateWranglerConfig, getPresetAliases, getPresetNames, getRegisteredPresets, listDetectablePresets, nodePreset, registerBuiltinPresets, registerPreset, requireCapability, resolvePreset, resolvePresetByName, resolvePresetWithDetection, serializeWranglerToml, standardPreset };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ubean/preset",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "description": "Deployment presets for ubean (standard, node, cloudflare, wrangler config)",
5
5
  "files": [
6
6
  "dist"