diff --git a/edge/_shared/bundle/schema.ts b/edge/_shared/bundle/schema.ts index 4580823..7dc87fc 100644 --- a/edge/_shared/bundle/schema.ts +++ b/edge/_shared/bundle/schema.ts @@ -1,120 +1,179 @@ /** * Bundle Service Schemas * - * Zod schemas for request validation and response typing. + * Zod v4 schemas for request validation and response typing. * * @module */ import { z } from 'zod' +// ============================================================================= +// Shared Helpers +// ============================================================================= + +/** + * Query-string boolean: accepts `""`, `"true"`, `"false"`, or absent. + * + * Transforms to `true` when value is `""` or `"true"`, `false` when `"false"`, + * `undefined` when absent. This matches how query params behave in practice: + * `?tsx` (empty string) and `?tsx=true` are both truthy. + */ +const queryBool = () => + z + .enum(['', 'true', 'false']) + .optional() + .transform((v): boolean => v === '' || v === 'true') + +/** + * Tri-state query boolean: same as queryBool but preserves `undefined` + * when absent (rather than coercing to `false`). Used for params where + * "not specified" differs from "explicitly false". + */ +const queryTriBool = () => + z + .enum(['', 'true', 'false']) + .optional() + .transform((v): boolean | undefined => + v === '' || v === 'true' ? true : v === 'false' ? false : undefined + ) + // ============================================================================= // Query Parameter Schemas // ============================================================================= /** - * Schema for bundle query parameters. + * Schema for bundle query parameters (V4 DSL Spec v1). + * + * ## URL Structure + * + * ``` + * /?v=1&q=&base=&treeshake= + * ``` + * + * ### New in V4 + * + * - `v` — Spec version (always `1`). Canonical share links include this. + * - `base` — Default bracket payload for unoverridden modules. + * Missing = `auto|default` (namespace + default surface). * - * Validates the various query options supported by the bundle API. + * ### Bracket Grammar + * + * ``` + * bracket = emit_item ("|" emit_item)* + * emit_item = [phase] clause [attributes] + * phase = "defer" | "source" | "type" + * clause = "bare" | "auto" | "default" | "*" | "* as X" | "{ ... }" | "id:X" | X + * attributes = "with" "{" key:value, ... "}" + * ``` + * + * @see GRAMMAR.md for full spec */ export const BundleQuerySchema = z.object({ - /** Module specifier(s) - comma-separated */ - q: z.string().optional(), - query: z.string().optional(), - - /** Treeshake specification */ - treeshake: z.string().optional(), - - /** LZ-compressed code */ - share: z.string().optional(), - - /** Plain text code */ - text: z.string().optional(), - - /** JSON5 configuration */ - config: z.string().optional(), - - /** Enable JSX/TSX support */ - tsx: z - .union([z.literal(''), z.literal('true'), z.literal('false')]) - .optional() - .transform((v) => v === '' || v === 'true'), - jsx: z - .union([z.literal(''), z.literal('true'), z.literal('false')]) - .optional() - .transform((v) => v === '' || v === 'true'), - - /** Enable polyfills */ - polyfill: z - .union([z.literal(''), z.literal('true'), z.literal('false')]) - .optional() - .transform((v) => v === '' || v === 'true'), - - /** Minify output */ - minify: z - .union([z.literal(''), z.literal('true'), z.literal('false')]) - .optional() - .transform((v) => (v === '' ? true : v === 'true' ? true : v === 'false' ? false : undefined)), - - /** Pretty (non-minified) output */ - pretty: z - .union([z.literal(''), z.literal('true'), z.literal('false')]) - .optional() - .transform((v) => (v === '' ? true : v === 'true' ? true : v === 'false' ? false : undefined)), - - /** Source map generation */ - sourcemap: z - .union([z.literal(''), z.literal('true'), z.literal('false'), z.literal('inline'), z.literal('external'), z.literal('both')]) - .optional(), - - /** Output format */ - format: z.enum(['esm', 'cjs', 'iife']).optional(), - - /** Enable metafile output */ - metafile: z - .union([z.literal(''), z.literal('true'), z.literal('false')]) - .optional() - .transform((v) => v === '' || v === 'true'), - - /** Enable analysis output */ - analysis: z.string().optional(), - analyze: z.string().optional(), - - /** Badge generation */ - badge: z.string().optional(), - 'badge-style': z.string().optional(), - 'badge-raster': z - .union([z.literal(''), z.literal('true'), z.literal('false')]) - .optional() - .transform((v) => v === '' || v === 'true'), - png: z - .union([z.literal(''), z.literal('true'), z.literal('false')]) - .optional() - .transform((v) => v === '' || v === 'true'), - - /** File output */ - file: z - .union([z.literal(''), z.literal('true'), z.literal('false')]) - .optional() - .transform((v) => v === '' || v === 'true'), - - /** Raw JSON output */ - raw: z - .union([z.literal(''), z.literal('true'), z.literal('false')]) - .optional() - .transform((v) => v === '' || v === 'true'), - - /** Cache control mode */ - cache: z.enum(['use', 'bypass', 'refresh']).optional(), - - /** Warnings output */ - warnings: z - .union([z.literal(''), z.literal('true'), z.literal('false')]) - .optional() - .transform((v) => v === '' || v === 'true'), - warning: z - .union([z.literal(''), z.literal('true'), z.literal('false')]) - .optional() - .transform((v) => v === '' || v === 'true'), + // ------------------------------------------------------------------------- + // V4 DSL params + // ------------------------------------------------------------------------- + + /** + * Spec version. Always `1` for current grammar. + * Share links SHOULD always include this to lock interpretation. + */ + v: z + .string() + .optional() + .transform((v) => (v ? Number(v) : undefined)), + + /** + * Default bracket payload for modules without a treeshake override. + * + * Examples: + * - `auto` — safe namespace only (one line per module) + * - `auto|default` — namespace + default surface (two lines) + * - `*|{default}` — old-school re-export all + default + * - `type auto|type default` — type-only surfaces + * + * When missing, interpreted as `auto|default`. + */ + base: z.string().optional(), + + // ------------------------------------------------------------------------- + // Module & code params + // ------------------------------------------------------------------------- + + /** Module specifier(s) — comma-separated */ + q: z.string().optional(), + query: z.string().optional(), + + /** + * Per-module bracket payload overrides. + * + * Positional: `[auto|default],,[{parse}with{type:json}]` + * Sparse: `0:[auto|default];2:[{parse}with{type:json}]` + */ + treeshake: z.string().optional(), + + /** LZ-compressed code (for large input) */ + share: z.string().optional(), + + /** Plain text code (for short input) */ + text: z.string().optional(), + + /** JSON5 build configuration */ + config: z.string().optional(), + + // ------------------------------------------------------------------------- + // Build options + // ------------------------------------------------------------------------- + + /** Enable JSX/TSX support */ + tsx: queryBool(), + jsx: queryBool(), + + /** Enable polyfills */ + polyfill: queryBool(), + + /** Minify output */ + minify: queryTriBool(), + + /** Pretty (non-minified) output */ + pretty: queryTriBool(), + + /** Source map generation */ + sourcemap: z + .enum(['', 'true', 'false', 'inline', 'external', 'both']) + .optional(), + + /** Output format */ + format: z.enum(['esm', 'cjs', 'iife']).optional(), + + // ------------------------------------------------------------------------- + // Output mode params + // ------------------------------------------------------------------------- + + /** Enable metafile output */ + metafile: queryBool(), + + /** Enable analysis output */ + analysis: z.string().optional(), + analyze: z.string().optional(), + + /** Badge generation */ + badge: z.string().optional(), + 'badge-style': z.string().optional(), + 'badge-raster': queryBool(), + png: queryBool(), + + /** File output */ + file: queryBool(), + + /** Raw JSON output */ + raw: queryBool(), + + /** Cache control mode */ + cache: z.enum(['use', 'bypass', 'refresh']).optional(), + + /** Warnings output */ + warnings: queryBool(), + warning: queryBool(), }) export type BundleQuery = z.infer @@ -123,70 +182,60 @@ export type BundleQuery = z.infer // Response Schemas // ============================================================================= -/** - * Schema for compression size information. - */ +/** Compression size information */ export const CompressionSizeSchema = z.object({ - type: z.string(), - uncompressedSize: z.string(), - compressedSize: z.string(), - rawUncompressedSize: z.number(), - rawCompressedSize: z.number(), + type: z.string(), + uncompressedSize: z.string(), + compressedSize: z.string(), + rawUncompressedSize: z.number(), + rawCompressedSize: z.number(), }) -/** - * Schema for install size information. - */ +/** Install size information */ export const InstallSizeSchema = z.object({ - total: z.number().optional(), - packages: z - .array( - z.object({ - name: z.string(), - size: z.number(), - }) - ) - .optional(), + total: z.number().optional(), + packages: z + .array( + z.object({ + name: z.string(), + size: z.number(), + }) + ) + .optional(), }) -/** - * Schema for module specification. - */ +/** Module specification tuple: [specifier, mode] */ export const ModuleSpecSchema = z.tuple([ - z.string(), // specifier - z.string(), // mode + z.string(), + z.string(), ]) -/** - * Schema for bundle result response. - */ +/** Bundle result response */ export const BundleResultSchema = z.object({ - query: z.string(), - rawQuery: z.string(), - config: z.record(z.string(), z.unknown()), - input: z.string(), - version: z.string().optional(), - versions: z.array(z.string()).optional(), - modules: z.array(ModuleSpecSchema).optional(), - size: CompressionSizeSchema, - installSize: InstallSizeSchema.optional(), - time: z.string(), - rawTime: z.number(), - fileId: z.string().optional(), - fileUrl: z.string().optional(), - fileHTMLUrl: z.string().optional(), - warnings: z.array(z.string()).optional(), - metafile: z.record(z.string(), z.unknown()).optional(), - cached: z.boolean().optional(), + query: z.string(), + rawQuery: z.string(), + config: z.record(z.string(), z.unknown()), + input: z.string(), + version: z.string().optional(), + versions: z.array(z.string()).optional(), + modules: z.array(ModuleSpecSchema).optional(), + size: CompressionSizeSchema, + installSize: InstallSizeSchema.optional(), + time: z.string(), + rawTime: z.number(), + fileId: z.string().optional(), + fileUrl: z.string().optional(), + fileHTMLUrl: z.string().optional(), + warnings: z.array(z.string()).optional(), + metafile: z.record(z.string(), z.unknown()).optional(), + cached: z.boolean().optional(), }) export type BundleResultResponse = z.infer -/** - * Schema for error response. - */ +/** Error response */ export const ErrorResponseSchema = z.object({ - error: z.string(), + error: z.string(), }) export type ErrorResponse = z.infer @@ -195,13 +244,10 @@ export type ErrorResponse = z.infer // Documentation Schema // ============================================================================= -/** - * Schema for API documentation (shown when no query provided). - */ export const DocsSchema = z.object({ - docs: z.string(), - examples: z.array(z.string()), - basics: z.array(z.string()), + docs: z.string(), + examples: z.array(z.string()), + basics: z.array(z.string()), }) export type Docs = z.infer @@ -210,47 +256,65 @@ export type Docs = z.infer * API documentation content. */ export const API_DOCS: Docs = { - docs: '/?docs - Takes you to some docs for the API', - examples: [ - '(new) /?tsx or /?jsx', - '(new) /?badge or /?badge=detailed or /?badge=minified', - '(new) /?badge-style=for-the-badge', - '(new) /?badge-raster', - '(new) /?file', - '(new) /?polyfill', - '(new) /?analysis or /?analyze=verbose', - '(new) /?metafile', - '(new) /?minify=false', - '(new) /?sourcemap=inline', - '(new) /?format=iife', - '(new) /?warnings', - '(new) /?raw', - '~~~', - '/?q=spring-easing,(import)@okikio/emitter,(import)@okikio/animate,(import)@okikio/animate,(import)@okikio/animate,(import)@okikio/animate,@okikio/animate,typescript@beta,vue,react', - '/?treeshake=[SpringEasing],[T],[{ animate }],[{ animate as B }],[* as TR],[{ type animate }],[*],[*],[*],[*]', - '/?text="export * as PR18 from \\"@okikio/animate\\";\\nexport { animate as animate2 } from \\"@okikio/animate\\";"', - '/?share=MYewdgziA2CmB00QHMAUAiAwiG6CUQA', - '/?config={"cdn":"skypack","compression":"brotli","esbuild":{"format":"cjs","minify":false,"treeShaking":false}}', - ], - basics: [ - '(new) /?tsx or /?jsx - Support JSX and TSX. Used to be built-in but decided to make it optional, as it caused errors in non TSX packages', - '(new) /?badge - Generates a badge (if you want more details, set `?badge=detailed` (to list the modules being bundled in the badge) or `?badge=minified` for the minified bundle size)', - '(new) /?badge-style - Various badge styles supported by http://shields.io (https://shields.io/#:~:text=PREFIX%3E%26suffix%3D%3CSUFFIX%3E-,Styles,-The%20following%20styles)', - '(new) /?badge-raster - The badge but as a png image', - '(new) /?file - Resulting bundled code(you can actually import this into your javascript file and start using it https://stackblitz.com/edit/vitejs-vite-iquaht?file=src%2Fmain.ts&terminal=dev)', - '(new) /?polyfill - Polyfill Node built-ins', - '(new) /?analysis or /?analyze - Esbuild generate visual analysis https://esbuild.github.io/api/#analyze', - '(new) /?metafile - Esbuild bundle metafile which can be used w / https://esbuild.github.io/analyze/ (hoping to have this built-in in the future)', - '(new) /?minify - Esbuild minify https://esbuild.github.io/api/#minify', - '(new) /?sourcemap - Esbuild sourcemap https://esbuild.github.io/api/#source-maps', - '(new) /?format - Esbuild format https://esbuild.github.io/api/#format', - '(new) /?warnings - Lists warning for a particular bundle', - '(new) /?raw - The raw result of the bundle (meant for experiments and/or testing)', - '~~~', - '/?q or /?query - Represents the module, e.g. react, vue, etc... You can add (import) in-front of a specific module to make it an import instead of an export', - '/?treeshake - Represents the export/imports to treeshake. The treeshake syntax allows for specifying multiple exports per package (check the example above). The square brackets represent seperate packages, and everything inside the square brackets, are the exported methods, types, etc...', - '/?text - Represents the input code as a string (it\'s meant for short strings, we recommend using `/?share` for longer strings)', - '/?share - Represents `compressed` string version of the input code (it\'s used for large input code)', - '/?config - Represents the configurations to use when building the bundle (the docs cover the config in detail https://blog.okikio.dev/documenting-an-online-bundler-bundlejs#heading-configuration)', - ], + docs: '/?docs - Takes you to some docs for the API', + examples: [ + '/?v=1', + '/?base=auto', + '/?base=auto|default', + '/?treeshake=[auto|default],,[{parse}with{type:json}]', + '/?treeshake=0:[auto];2:[defer*asX]', + '~~~', + '/?tsx or /?jsx', + '/?badge or /?badge=detailed or /?badge=minified', + '/?badge-style=for-the-badge', + '/?badge-raster', + '/?file', + '/?polyfill', + '/?analysis or /?analyze=verbose', + '/?metafile', + '/?minify=false', + '/?sourcemap=inline', + '/?format=iife', + '/?warnings', + '/?raw', + '~~~', + '/?q=spring-easing,(import)@okikio/emitter,(import)@okikio/animate', + '/?treeshake=[auto|default],[T],[{ animate }]', + '/?text="export * as PR18 from \\"@okikio/animate\\";\\nexport { animate as animate2 } from \\"@okikio/animate\\";"', + '/?share=MYewdgziA2CmB00QHMAUAiAwiG6CUQA', + '/?config={"cdn":"skypack","compression":"brotli","esbuild":{"format":"cjs","minify":false,"treeShaking":false}}', + ], + basics: [ + // V4 DSL params + '/?v — Spec version (currently v=1). Canonical share links always include this.', + '/?base — Default bracket payload for modules without a treeshake override. Missing = auto|default. Set base=auto for safe/minimal output (one line per module).', + '~~~', + // Treeshake grammar + '/?treeshake — Per-module bracket overrides. Supports positional ([auto],,[{parse}]) and sparse (0:[auto];2:[{parse}]) formats.', + ' Clauses: bare, auto, default, *, * as X, { named }, id:X, or an identifier', + ' Phases: defer (namespace only), source (identifier only), type (all except bare)', + ' Multi-emit: [auto|default] produces two statements (namespace + default surface)', + ' Attributes: [{parse}with{type:json}] adds import attributes', + ' Separators: spaces, +, _ between keywords all work. [*_as_X] = [* as X] = [*asX]', + '~~~', + // Existing params + '/?q or /?query — Module specifier(s), comma-separated. Prefix (import) for import mode, bare = export.', + '/?tsx or /?jsx — Support JSX and TSX', + '/?badge — Generates a badge (badge=detailed for module names, badge=minified for minified size)', + '/?badge-style — Badge styles from shields.io', + '/?badge-raster — Badge as PNG image', + '/?file — Resulting bundled code output', + '/?polyfill — Polyfill Node built-ins', + '/?analysis or /?analyze — Visual analysis via esbuild', + '/?metafile — Esbuild bundle metafile for https://esbuild.github.io/analyze/', + '/?minify — Esbuild minify (default true)', + '/?sourcemap — Esbuild sourcemap (inline, external, both)', + '/?format — Output format (esm, cjs, iife)', + '/?warnings — Lists warnings for a bundle', + '/?raw — Raw JSON result', + '/?text — Input code as a string (short strings; use share for longer)', + '/?share — LZ-compressed string version of input code', + '/?config — JSON5 build configuration', + '/?cache — Cache control: use (default), bypass, refresh', + ], } \ No newline at end of file diff --git a/edge/_shared/utils/parse-query.test.ts b/edge/_shared/utils/parse-query.test.ts new file mode 100644 index 0000000..d280a0d --- /dev/null +++ b/edge/_shared/utils/parse-query.test.ts @@ -0,0 +1,778 @@ +/** + * V4 Spec v1 test suite for parse-query. + * + * Run with: deno test parse-query.test.ts + */ + +import { + parseEmitItem, + parseBracket, + splitTreeshake, + buildInputCode, + getModuleName, + DEFAULT_BASE, +} from './parse-query.ts' +import { assertEquals } from 'jsr:@std/assert' + +// ============================================================================= +// parseEmitItem — clause forms +// ============================================================================= + +Deno.test('clause: bare', () => { + assertEquals(parseEmitItem('bare').specifier, { kind: 'bare' }) +}) + +Deno.test('clause: auto', () => { + assertEquals(parseEmitItem('auto').specifier, { kind: 'auto' }) +}) + +Deno.test('clause: *', () => { + assertEquals(parseEmitItem('*').specifier, { kind: 'star' }) +}) + +Deno.test('clause: * as X', () => { + assertEquals(parseEmitItem('* as X').specifier, { kind: 'namespace', name: 'X' }) +}) + +Deno.test('clause: { a, b }', () => { + assertEquals(parseEmitItem('{ a, b }').specifier, { kind: 'named', names: 'a, b' }) +}) + +Deno.test('clause: { type Config }', () => { + assertEquals(parseEmitItem('{ type Config }').specifier, { kind: 'named', names: 'type Config' }) +}) + +Deno.test('clause: default', () => { + assertEquals(parseEmitItem('default').specifier, { kind: 'default-surface', name: null }) +}) + +Deno.test('clause: default as React', () => { + assertEquals(parseEmitItem('default as React').specifier, { kind: 'default-surface', name: 'React' }) +}) + +Deno.test('clause: React (identifier)', () => { + assertEquals(parseEmitItem('React').specifier, { kind: 'identifier', name: 'React' }) +}) + +Deno.test('clause: id:defer (escape hatch)', () => { + const result = parseEmitItem('id:defer') + assertEquals(result.phase, null) + assertEquals(result.specifier, { kind: 'identifier', name: 'defer' }) +}) + +Deno.test('clause: id:bare (escape hatch)', () => { + const result = parseEmitItem('id:bare') + assertEquals(result.phase, null) + assertEquals(result.specifier, { kind: 'identifier', name: 'bare' }) +}) + +Deno.test('clause: id:type (escape hatch)', () => { + const result = parseEmitItem('id:type') + assertEquals(result.phase, null) + assertEquals(result.specifier, { kind: 'identifier', name: 'type' }) +}) + +Deno.test('clause: empty → auto', () => { + assertEquals(parseEmitItem('').specifier, { kind: 'auto' }) +}) + +// ============================================================================= +// parseEmitItem — defer phase +// ============================================================================= + +Deno.test('defer: * as X', () => { + const r = parseEmitItem('defer * as X') + assertEquals(r.phase, 'defer') + assertEquals(r.specifier, { kind: 'namespace', name: 'X' }) +}) + +Deno.test('defer: auto', () => { + const r = parseEmitItem('defer auto') + assertEquals(r.phase, 'defer') + assertEquals(r.specifier, { kind: 'auto' }) +}) + +Deno.test('defer: *', () => { + const r = parseEmitItem('defer *') + assertEquals(r.phase, 'defer') + assertEquals(r.specifier, { kind: 'star' }) +}) + +// ============================================================================= +// parseEmitItem — source phase +// ============================================================================= + +Deno.test('source: X (space form)', () => { + const r = parseEmitItem('source X') + assertEquals(r.phase, 'source') + assertEquals(r.specifier, { kind: 'identifier', name: 'X' }) +}) + +Deno.test('source: source:Wasm (colon form)', () => { + const r = parseEmitItem('source:Wasm') + assertEquals(r.phase, 'source') + assertEquals(r.specifier, { kind: 'identifier', name: 'Wasm' }) +}) + +Deno.test('source: auto', () => { + const r = parseEmitItem('source auto') + assertEquals(r.phase, 'source') + assertEquals(r.specifier, { kind: 'auto' }) +}) + +// ============================================================================= +// parseEmitItem — type phase +// ============================================================================= + +Deno.test('type: * as X', () => { + const r = parseEmitItem('type * as X') + assertEquals(r.phase, 'type') + assertEquals(r.specifier, { kind: 'namespace', name: 'X' }) +}) + +Deno.test('type: { Config, Theme }', () => { + const r = parseEmitItem('type { Config, Theme }') + assertEquals(r.phase, 'type') + assertEquals(r.specifier, { kind: 'named', names: 'Config, Theme' }) +}) + +Deno.test('type: X (identifier)', () => { + const r = parseEmitItem('type X') + assertEquals(r.phase, 'type') + assertEquals(r.specifier, { kind: 'identifier', name: 'X' }) +}) + +Deno.test('type: auto', () => { + const r = parseEmitItem('type auto') + assertEquals(r.phase, 'type') + assertEquals(r.specifier, { kind: 'auto' }) +}) + +Deno.test('type: default', () => { + const r = parseEmitItem('type default') + assertEquals(r.phase, 'type') + assertEquals(r.specifier, { kind: 'default-surface', name: null }) +}) + +Deno.test('type: *', () => { + const r = parseEmitItem('type *') + assertEquals(r.phase, 'type') + assertEquals(r.specifier, { kind: 'star' }) +}) + +Deno.test('type: default as ReactType', () => { + const r = parseEmitItem('type default as ReactType') + assertEquals(r.phase, 'type') + assertEquals(r.specifier, { kind: 'default-surface', name: 'ReactType' }) +}) + +// ============================================================================= +// parseEmitItem — attributes +// ============================================================================= + +Deno.test('attrs: braced compact {type:json}', () => { + const r = parseEmitItem('{ parse } with{type:json}') + assertEquals(r.specifier, { kind: 'named', names: 'parse' }) + assertEquals(r.attributes, { type: 'json' }) +}) + +Deno.test('attrs: braced spaced { type: json }', () => { + const r = parseEmitItem('{ parse } with { type: json }') + assertEquals(r.attributes, { type: 'json' }) +}) + +Deno.test('attrs: unbraced type:json', () => { + const r = parseEmitItem('{ parse } with type:json') + assertEquals(r.attributes, { type: 'json' }) +}) + +Deno.test('attrs: multiple pairs', () => { + const r = parseEmitItem('* as S with{type:css, integrity:sha256}') + assertEquals(r.attributes, { type: 'css', integrity: 'sha256' }) +}) + +Deno.test('attrs: bare with{type:css}', () => { + const r = parseEmitItem('bare with{type:css}') + assertEquals(r.specifier, { kind: 'bare' }) + assertEquals(r.attributes, { type: 'css' }) +}) + +Deno.test('attrs: quoted values stripped', () => { + const r = parseEmitItem('{ data } with{type:"json"}') + assertEquals(r.attributes, { type: 'json' }) +}) + +// ============================================================================= +// parseEmitItem — combined phase + clause + attrs +// ============================================================================= + +Deno.test('combined: defer * as X with{type:wasm}', () => { + const r = parseEmitItem('defer * as X with{type:wasm}') + assertEquals(r.phase, 'defer') + assertEquals(r.specifier, { kind: 'namespace', name: 'X' }) + assertEquals(r.attributes, { type: 'wasm' }) +}) + +Deno.test('combined: type { Config } with{type:json}', () => { + const r = parseEmitItem('type { Config } with{type:json}') + assertEquals(r.phase, 'type') + assertEquals(r.specifier, { kind: 'named', names: 'Config' }) + assertEquals(r.attributes, { type: 'json' }) +}) + +// ============================================================================= +// parseEmitItem — "with" inside braces is not attr marker +// ============================================================================= + +Deno.test('no false attr: { withCredentials, fetch }', () => { + const r = parseEmitItem('{ withCredentials, fetch }') + assertEquals(r.specifier, { kind: 'named', names: 'withCredentials, fetch' }) + assertEquals(r.attributes, null) +}) + +// ============================================================================= +// parseEmitItem — separator variants +// ============================================================================= + +Deno.test('sep: *_as_X', () => { + assertEquals(parseEmitItem('*_as_X').specifier, { kind: 'namespace', name: 'X' }) +}) + +Deno.test('sep: *asX (compact)', () => { + assertEquals(parseEmitItem('*asX').specifier, { kind: 'namespace', name: 'X' }) +}) + +Deno.test('sep: defer_*_as_X', () => { + const r = parseEmitItem('defer_*_as_X') + assertEquals(r.phase, 'defer') + assertEquals(r.specifier, { kind: 'namespace', name: 'X' }) +}) + +Deno.test('sep: defer*asX (fully compact)', () => { + const r = parseEmitItem('defer*asX') + assertEquals(r.phase, 'defer') + assertEquals(r.specifier, { kind: 'namespace', name: 'X' }) +}) + +Deno.test('sep: {parse}_with{type:json}', () => { + const r = parseEmitItem('{parse}_with{type:json}') + assertEquals(r.specifier, { kind: 'named', names: 'parse' }) + assertEquals(r.attributes, { type: 'json' }) +}) + +Deno.test('sep: {parse}with{type:json} (no separator)', () => { + const r = parseEmitItem('{parse}with{type:json}') + assertEquals(r.specifier, { kind: 'named', names: 'parse' }) + assertEquals(r.attributes, { type: 'json' }) +}) + +Deno.test('sep: type_*_as_X', () => { + const r = parseEmitItem('type_*_as_X') + assertEquals(r.phase, 'type') + assertEquals(r.specifier, { kind: 'namespace', name: 'X' }) +}) + +Deno.test('sep: default_as_React', () => { + assertEquals(parseEmitItem('default_as_React').specifier, { + kind: 'default-surface', + name: 'React', + }) +}) + +// ============================================================================= +// parseBracket — multi-emit with | +// ============================================================================= + +Deno.test('multi-emit: auto|default', () => { + const r = parseBracket('auto|default') + assertEquals(r.items.length, 2) + assertEquals(r.items[0].specifier, { kind: 'auto' }) + assertEquals(r.items[1].specifier, { kind: 'default-surface', name: null }) +}) + +Deno.test('multi-emit: *|default as React', () => { + const r = parseBracket('*|default as React') + assertEquals(r.items.length, 2) + assertEquals(r.items[0].specifier, { kind: 'star' }) + assertEquals(r.items[1].specifier, { kind: 'default-surface', name: 'React' }) +}) + +Deno.test('multi-emit: type auto|type default', () => { + const r = parseBracket('type auto|type default') + assertEquals(r.items.length, 2) + assertEquals(r.items[0].phase, 'type') + assertEquals(r.items[0].specifier, { kind: 'auto' }) + assertEquals(r.items[1].phase, 'type') + assertEquals(r.items[1].specifier, { kind: 'default-surface', name: null }) +}) + +Deno.test('empty bracket → auto', () => { + assertEquals(parseBracket('').items[0].specifier, { kind: 'auto' }) +}) + +// ============================================================================= +// splitTreeshake — positional format +// ============================================================================= + +Deno.test('positional: basic brackets', () => { + assertEquals(splitTreeshake('[{ animate }],[*]'), ['{ animate }', '*']) +}) + +Deno.test('positional: empty slots via ,,', () => { + const r = splitTreeshake('[auto],,[defer * as X],,[{parse}]') + assertEquals(r.length, 5) + assertEquals(r[0], 'auto') + assertEquals(r[1], '') + assertEquals(r[2], 'defer * as X') + assertEquals(r[3], '') + assertEquals(r[4], '{parse}') +}) + +// ============================================================================= +// splitTreeshake — sparse format +// ============================================================================= + +Deno.test('sparse: 0-based indices', () => { + const r = splitTreeshake('0:[auto];2:[defer*asX];4:[{parse}with{type:json}]') + assertEquals(r.length, 5) + assertEquals(r[0], 'auto') + assertEquals(r[1], undefined) + assertEquals(r[2], 'defer*asX') + assertEquals(r[3], undefined) + assertEquals(r[4], '{parse}with{type:json}') +}) + +Deno.test('sparse: single entry', () => { + const r = splitTreeshake('2:[{ animate }]') + assertEquals(r.length, 3) + assertEquals(r[0], undefined) + assertEquals(r[1], undefined) + assertEquals(r[2], '{ animate }') +}) + +// ============================================================================= +// buildInputCode — base= slot resolution +// ============================================================================= + +Deno.test('base: missing base = auto|default', () => { + const result = buildInputCode('react', undefined, undefined, undefined, undefined) + assertEquals(result, [ + '// Click Build for the Bundled, Minified & Compressed package size', + 'export * as react from "react";', + 'export { default as reactDefault } from "react";', + ].join('\n')) +}) + +Deno.test('base: explicit base=auto (safe, one line)', () => { + const result = buildInputCode('react', undefined, 'auto', undefined, undefined) + assertEquals(result, [ + '// Click Build for the Bundled, Minified & Compressed package size', + 'export * as react from "react";', + ].join('\n')) +}) + +Deno.test('base: explicit base=auto|default (same as missing)', () => { + const result = buildInputCode('react', undefined, 'auto|default', undefined, undefined) + assertEquals(result, [ + '// Click Build for the Bundled, Minified & Compressed package size', + 'export * as react from "react";', + 'export { default as reactDefault } from "react";', + ].join('\n')) +}) + +Deno.test('base: multi-module all get base', () => { + const result = buildInputCode('react,vue', undefined, 'auto', undefined, undefined) + assertEquals(result, [ + '// Click Build for the Bundled, Minified & Compressed package size', + 'export * as react from "react";', + 'export * as vue from "vue";', + ].join('\n')) +}) + +Deno.test('base: treeshake overrides specific slots, rest get base', () => { + const result = buildInputCode( + 'react,vue,angular', + '1:[{ createApp }]', + 'auto', + undefined, + undefined, + ) + assertEquals(result, [ + '// Click Build for the Bundled, Minified & Compressed package size', + 'export * as react from "react";', + 'export { createApp } from "vue";', + 'export * as angular from "angular";', + ].join('\n')) +}) + +Deno.test('base: base=* gives bare re-export all', () => { + const result = buildInputCode('react', undefined, '*', undefined, undefined) + assertEquals(result, [ + '// Click Build for the Bundled, Minified & Compressed package size', + 'export * from "react";', + ].join('\n')) +}) + +Deno.test('base: base=*|{default} gives old-school re-export', () => { + const result = buildInputCode('react', undefined, '*|{default}', undefined, undefined) + assertEquals(result, [ + '// Click Build for the Bundled, Minified & Compressed package size', + 'export * from "react";', + 'export { default } from "react";', + ].join('\n')) +}) + +Deno.test('base: import mode uses base too', () => { + const result = buildInputCode('(import)react', undefined, 'auto', undefined, undefined) + assertEquals(result, [ + '// Click Build for the Bundled, Minified & Compressed package size', + 'import * as react from "react";', + ].join('\n')) +}) + +Deno.test('base: import with base=auto|default', () => { + const result = buildInputCode('(import)react', undefined, 'auto|default', undefined, undefined) + assertEquals(result, [ + '// Click Build for the Bundled, Minified & Compressed package size', + 'import * as react from "react";', + 'import reactDefault from "react";', + ].join('\n')) +}) + +// ============================================================================= +// buildInputCode — type phase (imports) +// ============================================================================= + +Deno.test('type import: type * as X', () => { + const result = buildInputCode('(import)@types/react', '[type * as React]', undefined, undefined, undefined) + assertEquals(result, [ + '// Click Build for the Bundled, Minified & Compressed package size', + 'import type * as React from "@types/react";', + ].join('\n')) +}) + +Deno.test('type import: type { Config, Theme }', () => { + const result = buildInputCode('(import)@lib/types', '[type { Config, Theme }]', undefined, undefined, undefined) + assertEquals(result, [ + '// Click Build for the Bundled, Minified & Compressed package size', + 'import type { Config, Theme } from "@lib/types";', + ].join('\n')) +}) + +Deno.test('type import: type React (identifier)', () => { + const result = buildInputCode('(import)react', '[type React]', undefined, undefined, undefined) + assertEquals(result, [ + '// Click Build for the Bundled, Minified & Compressed package size', + 'import type React from "react";', + ].join('\n')) +}) + +Deno.test('type import: type auto', () => { + const result = buildInputCode('(import)react', '[type auto]', undefined, undefined, undefined) + assertEquals(result, [ + '// Click Build for the Bundled, Minified & Compressed package size', + 'import type * as react from "react";', + ].join('\n')) +}) + +Deno.test('type import: type default', () => { + const result = buildInputCode('(import)react', '[type default]', undefined, undefined, undefined) + assertEquals(result, [ + '// Click Build for the Bundled, Minified & Compressed package size', + 'import type reactDefault from "react";', + ].join('\n')) +}) + +Deno.test('type import: type bare → drops phase (invalid)', () => { + const result = buildInputCode('(import)react', '[type bare]', undefined, undefined, undefined) + // type + bare is invalid, phase dropped → bare import without type + assertEquals(result, [ + '// Click Build for the Bundled, Minified & Compressed package size', + 'import "react";', + ].join('\n')) +}) + +// ============================================================================= +// buildInputCode — type phase (exports — NOT dropped) +// ============================================================================= + +Deno.test('type export: type { Config }', () => { + const result = buildInputCode('@lib/types', '[type { Config }]', undefined, undefined, undefined) + assertEquals(result, [ + '// Click Build for the Bundled, Minified & Compressed package size', + 'export type { Config } from "@lib/types";', + ].join('\n')) +}) + +Deno.test('type export: type * as Types', () => { + const result = buildInputCode('@lib/types', '[type * as Types]', undefined, undefined, undefined) + assertEquals(result, [ + '// Click Build for the Bundled, Minified & Compressed package size', + 'export type * as Types from "@lib/types";', + ].join('\n')) +}) + +Deno.test('type export: type auto', () => { + const result = buildInputCode('@lib/types', '[type auto]', undefined, undefined, undefined) + assertEquals(result, [ + '// Click Build for the Bundled, Minified & Compressed package size', + 'export type * as libTypes from "@lib/types";', + ].join('\n')) +}) + +Deno.test('type export: type *', () => { + const result = buildInputCode('@lib/types', '[type *]', undefined, undefined, undefined) + assertEquals(result, [ + '// Click Build for the Bundled, Minified & Compressed package size', + 'export type * from "@lib/types";', + ].join('\n')) +}) + +Deno.test('type export: type default', () => { + const result = buildInputCode('@lib/types', '[type default]', undefined, undefined, undefined) + assertEquals(result, [ + '// Click Build for the Bundled, Minified & Compressed package size', + 'export type { default as libTypesDefault } from "@lib/types";', + ].join('\n')) +}) + +// ============================================================================= +// buildInputCode — defer/source phases (import only, dropped on export) +// ============================================================================= + +Deno.test('defer import: defer * as Lazy', () => { + const result = buildInputCode('(import)./lazy.js', '[defer * as Lazy]', undefined, undefined, undefined) + assertEquals(result, [ + '// Click Build for the Bundled, Minified & Compressed package size', + 'import defer * as Lazy from "./lazy.js";', + ].join('\n')) +}) + +Deno.test('source import: source:Wasm', () => { + const result = buildInputCode('(import)./mod.wasm', '[source:Wasm]', undefined, undefined, undefined) + assertEquals(result, [ + '// Click Build for the Bundled, Minified & Compressed package size', + 'import source Wasm from "./mod.wasm";', + ].join('\n')) +}) + +Deno.test('defer on export → phase dropped', () => { + const result = buildInputCode('lodash', '[defer * as _]', undefined, undefined, undefined) + assertEquals(result, [ + '// Click Build for the Bundled, Minified & Compressed package size', + 'export * as _ from "lodash";', + ].join('\n')) +}) + +Deno.test('source on export → phase dropped', () => { + const result = buildInputCode('lodash', '[source:_]', undefined, undefined, undefined) + // source + identifier on export → phase dropped, identifier becomes default alias + assertEquals(result, [ + '// Click Build for the Bundled, Minified & Compressed package size', + 'export { default as _ } from "lodash";', + ].join('\n')) +}) + +Deno.test('defer invalid clause → phase dropped', () => { + const result = buildInputCode('(import)pkg', '[defer { a }]', undefined, undefined, undefined) + assertEquals(result, [ + '// Click Build for the Bundled, Minified & Compressed package size', + 'import { a } from "pkg";', + ].join('\n')) +}) + +Deno.test('source invalid clause → phase dropped', () => { + const result = buildInputCode('(import)pkg', '[source * as X]', undefined, undefined, undefined) + assertEquals(result, [ + '// Click Build for the Bundled, Minified & Compressed package size', + 'import * as X from "pkg";', + ].join('\n')) +}) + +// ============================================================================= +// buildInputCode — attributes +// ============================================================================= + +Deno.test('import attrs: {parse} with{type:json}', () => { + const result = buildInputCode('(import)./data.json', '[{parse} with{type:json}]', undefined, undefined, undefined) + assertEquals(result, [ + '// Click Build for the Bundled, Minified & Compressed package size', + 'import { parse } from "./data.json" with { type: "json" };', + ].join('\n')) +}) + +Deno.test('export attrs: * as Styles with{type:css}', () => { + const result = buildInputCode('./styles.css', '[* as Styles with{type:css}]', undefined, undefined, undefined) + assertEquals(result, [ + '// Click Build for the Bundled, Minified & Compressed package size', + 'export * as Styles from "./styles.css" with { type: "css" };', + ].join('\n')) +}) + +Deno.test('bare import attrs: bare with{type:css}', () => { + const result = buildInputCode('(import)./styles.css', '[bare with{type:css}]', undefined, undefined, undefined) + assertEquals(result, [ + '// Click Build for the Bundled, Minified & Compressed package size', + 'import "./styles.css" with { type: "css" };', + ].join('\n')) +}) + +// ============================================================================= +// buildInputCode — sparse treeshake + base +// ============================================================================= + +Deno.test('sparse + base: override slots, rest use base', () => { + const result = buildInputCode( + '(import)data.json,(import)styles.css,@okikio/animate', + '0:[{parse} with{type:json}];1:[bare with{type:css}]', + 'auto', + undefined, + undefined, + ) + assertEquals(result, [ + '// Click Build for the Bundled, Minified & Compressed package size', + 'import { parse } from "data.json" with { type: "json" };', + 'import "styles.css" with { type: "css" };', + 'export * as okikioAnimate from "@okikio/animate";', + ].join('\n')) +}) + +// ============================================================================= +// buildInputCode — positional empty slots + base +// ============================================================================= + +Deno.test('positional empty slots use base', () => { + const result = buildInputCode( + 'react,vue,angular', + '[{ useState }],,', + 'auto', + undefined, + undefined, + ) + assertEquals(result, [ + '// Click Build for the Bundled, Minified & Compressed package size', + 'export { useState } from "react";', + 'export * as vue from "vue";', + 'export * as angular from "angular";', + ].join('\n')) +}) + +// ============================================================================= +// Backward compat — classic URLs still work +// ============================================================================= + +Deno.test('compat: existing import/export URL with treeshake', () => { + const result = buildInputCode( + '(import)@okikio/emitter,(import)@okikio/animate', + '[T],[{ animate }]', + undefined, + undefined, + undefined, + ) + assertEquals(result, [ + '// Click Build for the Bundled, Minified & Compressed package size', + 'import T from "@okikio/emitter";', + 'import { animate } from "@okikio/animate";', + ].join('\n')) +}) + +Deno.test('compat: existing namespace treeshake format', () => { + const result = buildInputCode( + '(import)@okikio/animate,(import)@okikio/animate', + '[{ animate as B }],[* as TR]', + undefined, + undefined, + undefined, + ) + assertEquals(result, [ + '// Click Build for the Bundled, Minified & Compressed package size', + 'import { animate as B } from "@okikio/animate";', + 'import * as TR from "@okikio/animate";', + ].join('\n')) +}) + +// ============================================================================= +// Realistic full URL scenarios +// ============================================================================= + +Deno.test('scenario: defer + source + JSON attrs (doc3)', () => { + const result = buildInputCode( + '(import)lodash,(import)./config.json,(import)wasm-tools', + '[defer*asLodash],[{settings}with{type:json}],[source:WasmTools]', + undefined, + undefined, + undefined, + ) + assertEquals(result, [ + '// Click Build for the Bundled, Minified & Compressed package size', + 'import defer * as Lodash from "lodash";', + 'import { settings } from "./config.json" with { type: "json" };', + 'import source WasmTools from "wasm-tools";', + ].join('\n')) +}) + +Deno.test('scenario: type exports + CSS attrs (doc3)', () => { + const result = buildInputCode( + '@lib/types,./theme.css', + '[type { Config, Theme }],[*_as_theme_with{type:css}]', + undefined, + undefined, + undefined, + ) + assertEquals(result, [ + '// Click Build for the Bundled, Minified & Compressed package size', + 'export type { Config, Theme } from "@lib/types";', + 'export * as theme from "./theme.css" with { type: "css" };', + ].join('\n')) +}) + +Deno.test('scenario: sparse + base=auto (doc5)', () => { + const result = buildInputCode( + 'react,react-dom/client,three', + '1:[auto|default];2:[{Scene,Mesh}]', + 'auto', + undefined, + undefined, + ) + assertEquals(result, [ + '// Click Build for the Bundled, Minified & Compressed package size', + 'export * as react from "react";', + 'export * as reactDomClient from "react-dom/client";', + 'export { default as reactDomClientDefault } from "react-dom/client";', + 'export { Scene,Mesh } from "three";', + ].join('\n')) +}) + +Deno.test('scenario: v=1 canonical share link', () => { + // ?v=1&q=react,react-dom/client&base=auto|default + const result = buildInputCode( + 'react,react-dom/client', + undefined, + 'auto|default', + undefined, + undefined, + ) + assertEquals(result, [ + '// Click Build for the Bundled, Minified & Compressed package size', + 'export * as react from "react";', + 'export { default as reactDefault } from "react";', + 'export * as reactDomClient from "react-dom/client";', + 'export { default as reactDomClientDefault } from "react-dom/client";', + ].join('\n')) +}) + +Deno.test('scenario: all type exports', () => { + // ?v=1&q=@lib/types&base=type auto|type default + const result = buildInputCode( + '@lib/types', + undefined, + 'type auto|type default', + undefined, + undefined, + ) + assertEquals(result, [ + '// Click Build for the Bundled, Minified & Compressed package size', + 'export type * as libTypes from "@lib/types";', + 'export type { default as libTypesDefault } from "@lib/types";', + ].join('\n')) +}) \ No newline at end of file diff --git a/edge/_shared/utils/parse-query.ts b/edge/_shared/utils/parse-query.ts index cd41180..b51c22e 100644 --- a/edge/_shared/utils/parse-query.ts +++ b/edge/_shared/utils/parse-query.ts @@ -1,16 +1,57 @@ /** - * Query parsing utilities for bundlejs. - * - * Transforms raw URL query parameters into normalized bundle configuration. - * Handles: - * - Package parsing with import/export modes - * - Treeshake export extraction - * - Share URL decompression - * - Config JSON5 parsing + * Query parsing utilities for bundlejs (V4 Spec v1). + * + * Transforms URL query parameters into normalized bundle configuration. + * + * ## URL Structure + * + * ``` + * /?v=1&q=&base=&treeshake=&share=&text=&config= + * ``` + * + * ## Bracket Grammar + * + * Each bracket contains one or more emit-items separated by `|`: + * + * ``` + * bracket = emit_item ("|" emit_item)* + * emit_item = [phase] clause [attributes] + * + * phase = "defer" (import: namespace/auto/star only) + * | "source" (import: identifier/auto only) + * | "type" (import+export: all clauses except bare) + * + * clause = "bare" → side-effect import / degrades on export + * | "auto" → safe auto-named namespace + * | "default" ["as" ] → default surface (auto or explicit name) + * | "*" → namespace auto-named (import) / re-export all (export) + * | "* as" → explicit namespace + * | "{ }" → named (supports "type", "as") + * | "id:" → identifier (keyword escape hatch) + * | → default binding / aliased default export + * + * attributes = "with" ["{"] kv ("," kv)* ["}"] + * where kv = key ":" value + * ``` + * + * ## Slot Resolution + * + * For each module q[i]: + * 1. If treeshake provides an override at index i → use it + * 2. Else → use `base` param + * 3. If `base` missing → use `auto|default` + * + * ## Phase Constraints + * + * - `defer`: import only, namespace/auto/star. Invalid combos drop phase. + * - `source`: import only, identifier/auto. Invalid combos drop phase. + * - `type`: import AND export, all clauses except bare. Invalid drops phase. + * - All phases silently dropped on export EXCEPT `type`. */ import type { BundleQuery } from '../bundle/schema.ts' import { lzstring, parsePackageName, deepMerge } from '@bundle/utils' +import { basename, extname } from '@bundle/utils/path' import JSON5 from '@bundle/utils/json5' const { decompressFromURL } = lzstring @@ -20,15 +61,41 @@ const { decompressFromURL } = lzstring // ============================================================================= export const DEFAULT_PACKAGE = 'spring-easing' +export const DEFAULT_BASE = 'auto|default' +export const SPEC_VERSION = 1 + +// ============================================================================= +// Types +// ============================================================================= + +export type ModuleEntry = { + pkg: string + mode: 'import' | 'export' +} + +export type ParsedEmitItem = { + phase: 'defer' | 'source' | 'type' | null + specifier: ClauseSpecifier + attributes: Record | null +} + +export type ParsedBracket = { + items: ParsedEmitItem[] +} -export const DEFAULT_INPUT = [ - 'export * from "spring-easing";', - 'export { default } from "spring-easing";', -].join('\n') +export type ClauseSpecifier = + | { kind: 'bare' } + | { kind: 'auto' } + | { kind: 'star' } + | { kind: 'namespace'; name: string } + | { kind: 'named'; names: string } + | { kind: 'default-surface'; name: string | null } + | { kind: 'identifier'; name: string } export type NormalizedBundleQuery = { + version: number packages: string[] - modules: Array<[string, 'import' | 'export']> + modules: ModuleEntry[] treeshakeExports: string[] exportAll: boolean inputCode: string @@ -42,76 +109,479 @@ export type NormalizedBundleQuery = { } // ============================================================================= -// Treeshake Parsing +// Treeshake Splitting (positional + sparse) // ============================================================================= /** - * Parse treeshake exports string into array. - * - * Format: `[{ x,y,z }],[*],[* as X],[{ type xyz }]` - * Each bracket group maps to a package in the query. - * - * @example - * ```ts - * parseTreeshakeExports('[{ animate }],[*]') - * // ['{ animate }', '*'] - * ``` + * Split treeshake string into per-index raw bracket strings. + * + * Auto-detects format: + * - Sparse: contains `N:[` → parse as 0-based index:content pairs + * - Positional: split on bracket boundaries, empty slots supported via `,, ` + * + * Returns sparse array. `undefined` = "no override, use base". + * Empty string = "explicit empty bracket, resolves to [auto]". */ -export function parseTreeshakeExports(str: string): string[] { - return (str ?? '') - .split(/\],/) - .map((s) => s.replace(/\[|\]/g, '').trim()) - .filter(Boolean) +export function splitTreeshake(str: string): Array { + const trimmed = (str ?? '').trim() + if (!trimmed) return [] + + if (/^\d+\s*:\s*\[/.test(trimmed)) { + return parseSparseTreeshake(trimmed) + } + + return parsePositionalTreeshake(trimmed) +} + +function parseSparseTreeshake(str: string): Array { + const result: Array = [] + const entries = splitOnChar(str, ';') + + for (const entry of entries) { + const match = /^(\d+)\s*:\s*\[(.*)]\s*$/.exec(entry.trim()) + if (!match) continue + const index = parseInt(match[1], 10) + const content = match[2].trim() + while (result.length <= index) result.push(undefined) + result[index] = content + } + + return result +} + +function parsePositionalTreeshake(str: string): Array { + const result: Array = [] + let depth = 0 + let current = '' + + for (let i = 0; i < str.length; i++) { + const ch = str[i] + + if (ch === '[') { + depth++ + if (depth === 1) continue // skip opening bracket + } else if (ch === ']') { + depth-- + if (depth === 0) { + result.push(current.trim()) + current = '' + if (str[i + 1] === ',') i++ // skip trailing comma + continue + } + } else if (ch === ',' && depth === 0) { + // Empty slot + if (current.trim() === '') { + result.push('') + } else { + result.push(current.trim()) + } + current = '' + continue + } + + current += ch + } + + if (current.trim()) result.push(current.trim()) + return result +} + +/** Split string on a char while respecting `{` `}` nesting. */ +function splitOnChar(str: string, sep: string): string[] { + const parts: string[] = [] + let depth = 0 + let current = '' + + for (const ch of str) { + if (ch === '{') depth++ + else if (ch === '}') depth-- + else if (ch === sep && depth === 0) { + parts.push(current) + current = '' + continue + } + current += ch + } + + if (current.trim()) parts.push(current) + return parts +} + +// Backward compat aliases +export { splitTreeshake as parseTreeshakeExports } + +export function splitTreeshakeBrackets(str: string): string[] { + return splitTreeshake(str).map((s) => s ?? '').filter(Boolean) } +// ============================================================================= +// Separator Normalization +// ============================================================================= + /** - * Check if treeshake exports indicate "export all". - * True when empty or all entries are `*` or `{ default }`. + * Normalize separators inside bracket content. + * + * URLSearchParams decodes `+` to space. We additionally treat `_` as a space + * between known keyword boundaries, but preserve it inside identifiers. + * + * Conservative approach: `_` only between keywords, not inside names like `my_lib`. */ -export function isExportAll(treeshakeArr: string[]): boolean { - if (treeshakeArr.length === 0) return true - return treeshakeArr.every((x) => /^\*$|^{\s*default\s*}$/.test(x)) +function normalizeSeparators(raw: string): string { + return raw + .replace(/\s+/g, ' ') + .trim() + // Phase keywords followed by _ + .replace(/^(defer|source|type)_/i, '$1 ') + // * _as_ or *as (compact) → * as + .replace(/\*[\s_]*as[\s_]+/g, '* as ') + .replace(/\*as(?=[A-Z_$])/g, '* as ') + // default_as → default as + .replace(/\bdefault[\s_]+as[\s_]+/g, 'default as ') + // } followed by _ or touching with → } with + .replace(/}[\s_]*with(?=[\s_{]|$)/g, '} with') + // keyword followed by _with → keyword with + .replace(/\b(bare|auto|\*)[\s_]+with(?=[\s_{]|$)/g, '$1 with') } // ============================================================================= -// Module Name Utilities +// Bracket & Emit-Item Parsing // ============================================================================= /** - * Extract basename without extension from a path or URL. + * Parse a bracket entry (may contain multiple emit-items via `|`). + * Empty/missing bracket resolves to `[auto]`. + */ +export function parseBracket(raw: string): ParsedBracket { + if (!raw || !raw.trim()) { + return { items: [{ phase: null, specifier: { kind: 'auto' }, attributes: null }] } + } + + const parts = splitOnChar(raw, '|') + const items = parts.map(parseEmitItem) + + return { + items: items.length > 0 + ? items + : [{ phase: null, specifier: { kind: 'auto' }, attributes: null }], + } +} + +/** + * Parse a single emit-item: `[phase] clause [attributes]` + */ +export function parseEmitItem(raw: string): ParsedEmitItem { + let remaining = normalizeSeparators(raw) + + // --- Phase extraction --- + let phase: ParsedEmitItem['phase'] = null + + // type phase: `type *`, `type { ... }`, `type X`, `type auto`, `type default` + const typeMatch = /^type[\s_]+/i.exec(remaining) + if (typeMatch && !remaining.startsWith('type:') && remaining !== 'type') { + const afterPhase = remaining.slice(typeMatch[0].length) + if (afterPhase.length > 0) { + phase = 'type' + remaining = afterPhase + } + } + + // defer phase: `defer *`, `defer auto`, `defer*asX` + if (!phase) { + const deferMatch = /^defer[\s_]*/i.exec(remaining) + if (deferMatch && !remaining.startsWith('defer:') && remaining !== 'defer') { + const afterPhase = remaining.slice(deferMatch[0].length) + if (afterPhase.length > 0) { + phase = 'defer' + remaining = afterPhase + } + } + } + + // source phase: `source X`, `source:X`, `source auto` + if (!phase) { + const sourceColonMatch = /^source:/i.exec(remaining) + const sourceSpaceMatch = /^source[\s_]+/i.exec(remaining) + if (sourceColonMatch) { + phase = 'source' + remaining = remaining.slice(sourceColonMatch[0].length) + } else if (sourceSpaceMatch && remaining !== 'source') { + const afterPhase = remaining.slice(sourceSpaceMatch[0].length) + if (afterPhase.length > 0) { + phase = 'source' + remaining = afterPhase + } + } + } + + // --- Attributes extraction --- + let attributes: Record | null = null + const withIdx = findWithKeyword(remaining) + if (withIdx !== -1) { + const attrStr = remaining.slice(withIdx + 4).trim() + attributes = parseAttributeString(attrStr) + remaining = remaining.slice(0, withIdx).trim() + } + + // --- Specifier parsing --- + const specifier = parseSpecifier(remaining) + + return { phase, specifier, attributes } +} + +/** + * Find `with` keyword at top-level (not inside braces). + * Matches `with{`, `with `, `with_` at brace depth 0 with word boundary. */ -function fromBasename(path: string): string { - const withoutProtocol = path.replace(/^https?:\/\//, '') - const parts = withoutProtocol.split('/') - const last = parts[parts.length - 1] || '' - const dotIdx = last.lastIndexOf('.') - return dotIdx > 0 ? last.slice(0, dotIdx) : last +function findWithKeyword(str: string): number { + let depth = 0 + for (let i = 0; i < str.length; i++) { + if (str[i] === '{') depth++ + else if (str[i] === '}') depth-- + else if (depth === 0 && i + 4 <= str.length) { + const slice = str.slice(i, i + 4) + if (slice.toLowerCase() === 'with') { + const after = str[i + 4] + const before = str[i - 1] + const validBefore = i === 0 || /[\s_}]/.test(before) + const validAfter = after === '{' || after === ' ' || after === '_' || after === undefined + if (validBefore && validAfter) return i + } + } + } + return -1 } /** - * Generate a clean module variable name from a package specifier. - * + * Parse `{key:value, key:value}` or `key:value, key:value` attribute string. + */ +function parseAttributeString(str: string): Record | null { + let inner = str.trim() + if (inner.startsWith('{') && inner.endsWith('}')) { + inner = inner.slice(1, -1).trim() + } + + const result: Record = {} + for (const pair of inner.split(',')) { + const colonIdx = pair.indexOf(':') + if (colonIdx === -1) continue + const key = pair.slice(0, colonIdx).trim() + const value = pair.slice(colonIdx + 1).trim().replace(/^["']|["']$/g, '') + if (key) result[key] = value + } + + return Object.keys(result).length > 0 ? result : null +} + +function parseSpecifier(str: string): ClauseSpecifier { + const trimmed = str.trim() + if (!trimmed) return { kind: 'auto' } + + if (trimmed === 'bare') return { kind: 'bare' } + if (trimmed === 'auto') return { kind: 'auto' } + if (trimmed === '*') return { kind: 'star' } + + if (trimmed === 'default') return { kind: 'default-surface', name: null } + const defaultAsMatch = /^default\s+as\s+(.+)$/i.exec(trimmed) + if (defaultAsMatch) return { kind: 'default-surface', name: defaultAsMatch[1].trim() } + + const nsMatch = /^\*\s*as\s+(.+)$/.exec(trimmed) + if (nsMatch) return { kind: 'namespace', name: nsMatch[1].trim() } + + if (trimmed.startsWith('{') && trimmed.endsWith('}')) { + return { kind: 'named', names: trimmed.slice(1, -1).trim() } + } + + if (trimmed.startsWith('id:')) { + return { kind: 'identifier', name: trimmed.slice(3).trim() } + } + + return { kind: 'identifier', name: trimmed } +} + +// ============================================================================= +// Phase Validation +// ============================================================================= + +/** + * Validate phase against specifier + mode constraints. + * + * - `defer`: import only, namespace/auto/star. Otherwise silently dropped. + * - `source`: import only, identifier/auto. Otherwise silently dropped. + * - `type`: import AND export, all clauses except bare. Otherwise dropped. + * + * Returns validated phase or null. + */ +function validatePhase( + phase: ParsedEmitItem['phase'], + specifier: ClauseSpecifier, + mode: 'import' | 'export', +): ParsedEmitItem['phase'] { + if (!phase) return null + + if (phase === 'type') { + // type is valid on both import and export + // but not with bare (import type "pkg" is not valid TS) + if (specifier.kind === 'bare') return null + return 'type' + } + + // defer and source are import-only + if (mode === 'export') return null + + if (phase === 'defer') { + if (specifier.kind === 'namespace' || specifier.kind === 'auto' || specifier.kind === 'star') { + return 'defer' + } + return null + } + + if (phase === 'source') { + if (specifier.kind === 'identifier' || specifier.kind === 'auto') { + return 'source' + } + return null + } + + return null +} + +// ============================================================================= +// Module Name Utilities +// ============================================================================= + +export function fromBasename(path: string): string { + const clean = path.replace(/^https?:\/\//, '') + return basename(clean, extname(clean)) +} + +/** + * Generate a clean JS variable name from a package specifier. + * * @example * ```ts - * getModuleName('@okikio/animate') // 'okikioAnimate' + * getModuleName('@okikio/animate') // 'okikioAnimate' * getModuleName('https://esm.sh/lodash/debounce') // 'debounce' + * getModuleName('@pkg/lib@2.1.0') // 'pkgLib_2_1_0' + * getModuleName('3d-force-graph') // '_3dForceGraph' * ``` */ export function getModuleName(str: string): string { - const { name, path } = parsePackageName(str, { ignoreError: true }) - let base = str + let version: string | null = null + + try { + const parsed = parsePackageName(str) + base = parsed.name + (parsed.path ? fromBasename(parsed.path) : '') + version = parsed.version + } catch { + // URL or unparseable + } + if (/^https?:\/\//.test(str)) { base = fromBasename(str) - } else if (name.length > 0) { - base = name + (path ? fromBasename(path) : '') } - - return base + + let result = base .split(/[-_\/]/g) - .map((x, i) => (i > 0 && x.length > 0 ? x[0].toUpperCase() + x.slice(1) : x)) + .map((seg, i) => + i > 0 && seg.length > 0 ? seg[0].toUpperCase() + seg.slice(1) : seg + ) .join('') .replace(/[^\w]/gi, '') + + if (version) { + result += '_' + version.replace(/[^a-zA-Z0-9_]/g, '_') + } + + if (/^\d/.test(result)) { + result = '_' + result + } + + return result +} + +// ============================================================================= +// Statement Generation +// ============================================================================= + +function formatAttrs(attrs: Record | null): string { + if (!attrs) return '' + const pairs = Object.entries(attrs) + .map(([k, v]) => `${k}: "${v}"`) + .join(', ') + return ` with { ${pairs} }` +} + +function generateImportStatement( + moduleName: string, + item: ParsedEmitItem, +): string[] { + const attrs = formatAttrs(item.attributes) + const phase = validatePhase(item.phase, item.specifier, 'import') + const phaseStr = phase ? `${phase} ` : '' + const alias = getModuleName(moduleName) + + switch (item.specifier.kind) { + case 'bare': + return [`import ${phaseStr}"${moduleName}"${attrs};`] + + case 'auto': + case 'star': + return [`import ${phaseStr}* as ${alias} from "${moduleName}"${attrs};`] + + case 'namespace': + return [`import ${phaseStr}* as ${item.specifier.name} from "${moduleName}"${attrs};`] + + case 'named': + return [`import ${phaseStr}{ ${item.specifier.names} } from "${moduleName}"${attrs};`] + + case 'default-surface': { + const name = item.specifier.name ?? `${alias}Default` + return [`import ${phaseStr}${name} from "${moduleName}"${attrs};`] + } + + case 'identifier': + return [`import ${phaseStr}${item.specifier.name} from "${moduleName}"${attrs};`] + } +} + +function generateExportStatement( + moduleName: string, + item: ParsedEmitItem, +): string[] { + const attrs = formatAttrs(item.attributes) + // Only type phase survives on exports + const phase = validatePhase(item.phase, item.specifier, 'export') + const phaseStr = phase ? `${phase} ` : '' + const alias = getModuleName(moduleName) + + switch (item.specifier.kind) { + case 'bare': + // bare on export degrades to auto + return [`export ${phaseStr}* as ${alias} from "${moduleName}"${attrs};`] + + case 'auto': + return [`export ${phaseStr}* as ${alias} from "${moduleName}"${attrs};`] + + case 'star': + return [`export ${phaseStr}* from "${moduleName}"${attrs};`] + + case 'namespace': + return [`export ${phaseStr}* as ${item.specifier.name} from "${moduleName}"${attrs};`] + + case 'named': { + const names = item.specifier.names.trim() + return [`export ${phaseStr}{ ${names} } from "${moduleName}"${attrs};`] + } + + case 'default-surface': { + const name = item.specifier.name ?? `${alias}Default` + return [`export ${phaseStr}{ default as ${name} } from "${moduleName}"${attrs};`] + } + + case 'identifier': + return [`export ${phaseStr}{ default as ${item.specifier.name} } from "${moduleName}"${attrs};`] + } } // ============================================================================= @@ -119,84 +589,98 @@ export function getModuleName(str: string): string { // ============================================================================= /** - * Parse share URL query params into input code. - * - * Combines: - * - `q` / `query`: Package exports - * - `treeshake`: Specific exports per package - * - `share`: LZ-compressed additional code - * - `text`: Plaintext additional code + * Build the full input code string from parsed query components. + * + * Slot resolution for each module q[i]: + * 1. treeshake override at index i → use it + * 2. else → base param + * 3. else → DEFAULT_BASE ("auto|default") */ -export function parseShareURLQuery( +export function buildInputCode( query: string | undefined, treeshake: string | undefined, + base: string | undefined, share: string | undefined, - text: string | undefined + text: string | undefined, ): string { - const counts = new Map() let result = '' if (query) { const queryArr = query.trim().split(',') - const treeshakeArr = parseTreeshakeExports((treeshake ?? '').trim()) - const queryArrLen = queryArr.length - - result += - '// Click Build for the Bundled, Minified & Compressed package size\n' + - queryArr - .map((q, i) => { - const treeshakeExports = - treeshakeArr[i] && treeshakeArr[i].trim() !== '*' - ? treeshakeArr[i].trim().split(',').join(', ') - : '*' - - // Extract declaration mode: (import)pkg or (export)pkg or just pkg - const match = /^(\((.*)\))?(.*)/.exec(q)! - const declaration = match[2] || 'export' - const module = match[3] - - // Track duplicate module imports for unique naming - if (!counts.has(module)) counts.set(module, 0) - const count = counts.set(module, counts.get(module)! + 1).get(module)! - 1 - const countStr = count <= 0 ? '' : String(count) - - // Generate export/import statement - const moduleStr = JSON5.stringify(module) - const needsAlias = declaration === 'import' || queryArrLen > 1 - - let line = `${declaration} ${treeshakeExports} from ${moduleStr};` - - // Add default export if no specific treeshake - if ((treeshake ?? '').trim().length <= 0) { - const defaultAlias = needsAlias ? `as ${getModuleName(module)}Default${countStr} ` : '' - line += `\n${declaration} { default ${defaultAlias}} from ${moduleStr};` - } - - return line + const hasTreeshake = treeshake != null && treeshake.trim().length > 0 + + // Parse treeshake overrides (sparse array) + const overrides = hasTreeshake ? splitTreeshake(treeshake!) : [] + + // Parse the base bracket (fallback for unoverridden slots) + const baseBracket = parseBracket(base ?? DEFAULT_BASE) + + // Deduplicate when no treeshake AND no explicit base. + // With overrides or custom base, dupes may be intentional. + let entries: Array<{ raw: string; index: number }> + if (!hasTreeshake && !base) { + const seen = new Set() + entries = queryArr + .map((raw, index) => ({ raw, index })) + .filter(({ raw }) => { + const pkg = raw.startsWith('(import)') + ? raw.slice('(import)'.length) + : raw + if (seen.has(pkg)) return false + seen.add(pkg) + return true }) - .join('\n') + } else { + entries = queryArr.map((raw, index) => ({ raw, index })) + } + + const lines = entries + .map(({ raw, index }) => { + const trimmed = raw.trim() + const isImport = trimmed.startsWith('(import)') + const moduleName = (isImport ? trimmed.slice('(import)'.length) : trimmed).trim() + + if (!moduleName) return '' + + // Slot resolution: override → base + const overrideRaw = overrides[index] + const bracket = overrideRaw !== undefined + ? parseBracket(overrideRaw) + : baseBracket + + const stmts = bracket.items.flatMap((item) => + isImport + ? generateImportStatement(moduleName, item) + : generateExportStatement(moduleName, item) + ) + + return stmts.join('\n') + }) + .filter(Boolean) + + if (lines.length > 0) { + result += '// Click Build for the Bundled, Minified & Compressed package size\n' + result += lines.join('\n') + } } - // Decompress share param (LZ-string encoded) if (share) { try { - result += '\n' + decompressFromURL(share.trim()) + const decompressed = decompressFromURL(share.trim()) + if (decompressed) result += '\n' + decompressed } catch (e) { console.warn('[parse-query] Failed to decompress share param:', e) } } - // Parse text param (JSON5 string or raw) if (text) { try { - // Support both quoted and unquoted plaintext const isQuoted = /^["']/.test(text) && /["']$/.test(text) const parsed = isQuoted ? JSON5.parse(text) : JSON5.parse(JSON5.stringify(text).replace(/\\\\/g, '\\')) result += '\n' + parsed - } catch (_) { - // Fallback to raw text + } catch { result += '\n' + text } } @@ -205,15 +689,11 @@ export function parseShareURLQuery( } // ============================================================================= -// Config Parsing +// Config & Helpers // ============================================================================= -/** - * Parse config query param into build configuration object. - */ export function parseConfig(configStr: string | undefined): Record { if (!configStr) return {} - try { return deepMerge({}, JSON5.parse(configStr)) } catch (e) { @@ -222,78 +702,71 @@ export function parseConfig(configStr: string | undefined): Record /^\*$|^{\s*default\s*}$|^auto$|^$/.test(x)) +} + // ============================================================================= // Main Normalizer // ============================================================================= -/** - * Normalize raw query parameters into structured bundle configuration. - */ export function normalizeBundleQuery(raw: BundleQuery): NormalizedBundleQuery { + // v is already transformed to number | undefined by schema + const version = raw.v ?? SPEC_VERSION const queryStr = raw.q ?? raw.query ?? DEFAULT_PACKAGE const treeshakeStr = raw.treeshake + const baseStr = raw.base const shareStr = raw.share const textStr = raw.text - // Parse packages and their import/export modes - const packageEntries = queryStr.split(',').map((q) => { - const match = /^(\((\w+)\))?(.*)/.exec(q.trim())! - const mode = (match[2] || 'export') as 'import' | 'export' - const pkg = match[3] - return [pkg, mode] as [string, 'import' | 'export'] + const modules: ModuleEntry[] = queryStr.split(',').map((q) => { + const match = /^(?:\((\w+)\))?(.+)/.exec(q.trim()) + return { + mode: (match?.[1] || 'export') as 'import' | 'export', + pkg: match?.[2] ?? q.trim(), + } }) - const packages = packageEntries.map(([pkg]) => pkg) - const modules = packageEntries + const packages = modules.map((m) => m.pkg) - // Parse treeshake - const treeshakeExports = parseTreeshakeExports( - decodeURIComponent(treeshakeStr ?? '') - .trim() - .replace(/\s{2,}/g, ' ') + const treeshakeExports = splitTreeshakeBrackets( + decodeURIComponent(treeshakeStr ?? '').trim().replace(/\s{2,}/g, ' ') ) - const uniqueTreeshake = Array.from(new Set(treeshakeExports)) + const uniqueTreeshake = [...new Set(treeshakeExports)] const exportAll = !treeshakeStr || isExportAll(uniqueTreeshake) - // Generate input code const hasExplicitInput = Boolean(shareStr || textStr) - const inputCode = parseShareURLQuery( - hasExplicitInput ? undefined : queryStr, - treeshakeStr, - shareStr, - textStr - ) || DEFAULT_INPUT - - // Parse config + const inputCode = + buildInputCode( + hasExplicitInput ? undefined : queryStr, + treeshakeStr, + baseStr, + shareStr, + textStr, + ) || buildInputCode(DEFAULT_PACKAGE, undefined, DEFAULT_BASE, undefined, undefined) + const config = parseConfig(raw.config) - // Resolve boolean flags - const tsx = Boolean(raw.tsx || raw.jsx || (config as Record).tsx) - - // Minify: explicit minify=true/false, or inverse of pretty - let minify: boolean | undefined = undefined + // tsx/jsx/polyfill/metafile are already booleans from schema transforms + const tsx = raw.tsx || raw.jsx || Boolean((config as Record).tsx) + + // minify/pretty are boolean | undefined from schema tri-bool transform + let minify: boolean | undefined if (raw.minify !== undefined) { minify = raw.minify } else if (raw.pretty !== undefined) { minify = raw.pretty === false } - // Sourcemap - const sourcemap = raw.sourcemap ?? undefined - - // Format - const format = raw.format ?? undefined - - // Feature flags - const polyfill = Boolean(raw.polyfill) - const metafile = Boolean( + const metafile = raw.metafile || - raw.analysis || - raw.analyze || - (config as Record).analysis - ) + Boolean(raw.analysis) || + Boolean(raw.analyze) || + Boolean((config as Record).analysis) return { + version, packages, modules, treeshakeExports: uniqueTreeshake, @@ -302,9 +775,9 @@ export function normalizeBundleQuery(raw: BundleQuery): NormalizedBundleQuery { config, tsx, minify, - sourcemap, - format, - polyfill, + sourcemap: raw.sourcemap ?? undefined, + format: raw.format ?? undefined, + polyfill: raw.polyfill, metafile, } } \ No newline at end of file