@crab-dev/wake 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,20 @@
1
+ # Changelog
2
+
3
+ ## 0.1.2
4
+
5
+ - Updated the npm release pipeline for private GitHub repositories while preserving immutable tarball audits.
6
+
7
+ ## 0.1.1
8
+
9
+ - Fixed cross-platform output paths and source-map source names.
10
+ - Fixed concurrent documentation generation atomic-write races on Windows.
11
+ - Stabilized Windows native builds by pinning the NAPI-RS CLI.
12
+ - Aligned CI coverage with the supported Node.js 24 and 26 releases.
13
+
14
+ ## 0.1.0
15
+
16
+ - First Wake npm release.
17
+ - Added native build, bundle, build-context, dev-server, and documentation APIs.
18
+ - Added experimental tokenize, parse, transform, and semantic-analysis APIs.
19
+
20
+ The experimental subpath may change during the 0.x release series.
package/LICENSE-APACHE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/LICENSE-MIT ADDED
@@ -0,0 +1,25 @@
1
+ Copyright (c) 2014 Alex Crichton
2
+
3
+ Permission is hereby granted, free of charge, to any
4
+ person obtaining a copy of this software and associated
5
+ documentation files (the "Software"), to deal in the
6
+ Software without restriction, including without
7
+ limitation the rights to use, copy, modify, merge,
8
+ publish, distribute, sublicense, and/or sell copies of
9
+ the Software, and to permit persons to whom the Software
10
+ is furnished to do so, subject to the following
11
+ conditions:
12
+
13
+ The above copyright notice and this permission notice
14
+ shall be included in all copies or substantial portions
15
+ of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
18
+ ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
19
+ TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
20
+ PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
21
+ SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
22
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
23
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
24
+ IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
25
+ DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,27 @@
1
+ # @crab-dev/wake
2
+
3
+ Wake is a Rust-native web builder exposed as both a Node.js library and the
4
+ `wake` command.
5
+
6
+ ```sh
7
+ npm install --save-dev @crab-dev/wake
8
+ npx wake build
9
+ ```
10
+
11
+ ```js
12
+ import { build, startDevServer } from '@crab-dev/wake'
13
+
14
+ await build({ cwd: process.cwd() })
15
+
16
+ const server = await startDevServer({ port: 5173 })
17
+ console.log(server.url)
18
+ await server.waitUntilClosed()
19
+ ```
20
+
21
+ Compiler primitives are intentionally isolated under
22
+ `@crab-dev/wake/experimental`. A `ParsedModule` is an opaque, disposable
23
+ native handle and cannot be cloned, persisted, or transferred to a Worker.
24
+
25
+ Wake supports Node.js 22.14 through 26 on Windows x64, Linux glibc x64/arm64,
26
+ and macOS x64/arm64. Installing the package never compiles Rust code and does
27
+ not run a postinstall script.
package/bin/wake.mjs ADDED
@@ -0,0 +1,165 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { readFile } from 'node:fs/promises'
4
+ import {
5
+ build,
6
+ buildDocs,
7
+ startDevServer,
8
+ startDocsDevServer,
9
+ version,
10
+ } from '../index.mjs'
11
+ import { parse, tokenize } from '../experimental.mjs'
12
+
13
+ const HELP = `Wake ${version()}
14
+
15
+ Usage:
16
+ wake build [entry] [--outdir DIR] [--cache] [--sourcemap]
17
+ wake dev [root] [--entry FILE] [--host HOST] [--port PORT] [--open]
18
+ wake docs build [root] [--outdir DIR] [--base PATH]
19
+ wake docs dev [root] [--host HOST] [--port PORT] [--open]
20
+ wake parse <file>
21
+ wake tokenize <file>
22
+ wake --version
23
+ `
24
+
25
+ function takeOption(args, name) {
26
+ const index = args.indexOf(name)
27
+ if (index === -1) return undefined
28
+ if (index + 1 >= args.length) throw new Error(`${name} requires a value`)
29
+ const [value] = args.splice(index + 1, 1)
30
+ args.splice(index, 1)
31
+ return value
32
+ }
33
+
34
+ function takeFlag(args, name) {
35
+ const index = args.indexOf(name)
36
+ if (index === -1) return false
37
+ args.splice(index, 1)
38
+ return true
39
+ }
40
+
41
+ function commonOptions(args) {
42
+ return {
43
+ configPath: takeOption(args, '--config'),
44
+ }
45
+ }
46
+
47
+ function printResult(result) {
48
+ const files = result.files?.length || 0
49
+ console.log(
50
+ `wake: built ${result.moduleCount} modules and ${files} files in ${result.durationMs.toFixed(1)}ms`,
51
+ )
52
+ if (result.outputDir) console.log(`wake: output ${result.outputDir}`)
53
+ }
54
+
55
+ async function runServer(factory, options) {
56
+ const controller = new AbortController()
57
+ const server = await factory({ ...options, signal: controller.signal })
58
+ console.log(`wake: listening on ${server.url}`)
59
+
60
+ let stopping = false
61
+ const stop = async (signal) => {
62
+ if (stopping) return
63
+ stopping = true
64
+ controller.abort()
65
+ try {
66
+ await server.close()
67
+ } finally {
68
+ process.exitCode = signal === 'SIGINT' ? 130 : 143
69
+ }
70
+ }
71
+ process.once('SIGINT', () => void stop('SIGINT'))
72
+ process.once('SIGTERM', () => void stop('SIGTERM'))
73
+ await server.waitUntilClosed()
74
+ }
75
+
76
+ export async function runCli(argv = process.argv.slice(2)) {
77
+ const args = [...argv]
78
+ if (takeFlag(args, '--version') || takeFlag(args, '-V')) {
79
+ console.log(version())
80
+ return 0
81
+ }
82
+ if (args.length === 0 || takeFlag(args, '--help') || takeFlag(args, '-h')) {
83
+ console.log(HELP)
84
+ return 0
85
+ }
86
+
87
+ const command = args.shift()
88
+ if (command === 'build') {
89
+ const options = commonOptions(args)
90
+ options.outdir = takeOption(args, '--outdir')
91
+ options.cache = takeFlag(args, '--cache')
92
+ options.sourceMap = takeFlag(args, '--sourcemap')
93
+ if (args[0]) options.entry = args.shift()
94
+ if (args.length) throw new Error(`unknown build arguments: ${args.join(' ')}`)
95
+ printResult(await build(options))
96
+ return 0
97
+ }
98
+
99
+ if (command === 'dev') {
100
+ const options = commonOptions(args)
101
+ options.entry = takeOption(args, '--entry')
102
+ options.host = takeOption(args, '--host')
103
+ const port = takeOption(args, '--port')
104
+ if (port) options.port = Number(port)
105
+ options.open = takeFlag(args, '--open')
106
+ if (args[0]) options.cwd = args.shift()
107
+ if (args.length) throw new Error(`unknown dev arguments: ${args.join(' ')}`)
108
+ await runServer(startDevServer, options)
109
+ return process.exitCode || 0
110
+ }
111
+
112
+ if (command === 'docs') {
113
+ const action = args.shift()
114
+ const options = commonOptions(args)
115
+ options.outdir = takeOption(args, '--outdir')
116
+ options.basePath = takeOption(args, '--base')
117
+ options.host = takeOption(args, '--host')
118
+ const port = takeOption(args, '--port')
119
+ if (port) options.port = Number(port)
120
+ options.open = takeFlag(args, '--open')
121
+ if (args[0]) options.cwd = args.shift()
122
+ if (args.length) throw new Error(`unknown docs arguments: ${args.join(' ')}`)
123
+ if (action === 'build') {
124
+ printResult(await buildDocs(options))
125
+ return 0
126
+ }
127
+ if (action === 'dev') {
128
+ await runServer(startDocsDevServer, options)
129
+ return process.exitCode || 0
130
+ }
131
+ throw new Error('docs requires build or dev')
132
+ }
133
+
134
+ if (command === 'parse' || command === 'tokenize') {
135
+ const file = args.shift()
136
+ if (!file || args.length) throw new Error(`${command} requires one source file`)
137
+ const source = await readFile(file, 'utf8')
138
+ if (command === 'tokenize') {
139
+ console.log(JSON.stringify(tokenize(source), null, 2))
140
+ } else {
141
+ const module = parse(source, {
142
+ sourceType: file.endsWith('.cjs') ? 'script' : 'module',
143
+ })
144
+ try {
145
+ console.log(JSON.stringify(module.summary, null, 2))
146
+ } finally {
147
+ module.dispose()
148
+ }
149
+ }
150
+ return 0
151
+ }
152
+
153
+ throw new Error(`unknown command: ${command}`)
154
+ }
155
+
156
+ try {
157
+ process.exitCode = await runCli()
158
+ } catch (error) {
159
+ const code = error?.code ? `[${error.code}] ` : ''
160
+ console.error(`wake: ${code}${error?.message || error}`)
161
+ for (const diagnostic of error?.diagnostics || []) {
162
+ console.error(` ${diagnostic.severity}: ${diagnostic.message}`)
163
+ }
164
+ process.exitCode = 1
165
+ }
package/errors.cjs ADDED
@@ -0,0 +1,86 @@
1
+ 'use strict'
2
+
3
+ class WakeError extends Error {
4
+ constructor(code, message, options = {}) {
5
+ super(message, options.cause ? { cause: options.cause } : undefined)
6
+ this.name = 'WakeError'
7
+ this.code = code
8
+ if (options.path !== undefined) this.path = options.path
9
+ if (options.diagnostics !== undefined) this.diagnostics = options.diagnostics
10
+ }
11
+ }
12
+
13
+ function wakeError(value, cause) {
14
+ if (value instanceof WakeError) return value
15
+ const details = value && typeof value === 'object' ? value : {}
16
+ return new WakeError(
17
+ details.code || 'WAKE_INTERNAL',
18
+ details.message || String(value || 'Unknown Wake error'),
19
+ {
20
+ path: details.path,
21
+ diagnostics: details.diagnostics,
22
+ cause,
23
+ },
24
+ )
25
+ }
26
+
27
+ function fromNativeError(error) {
28
+ if (error && (error.name === 'AbortError' || error.code === 'ABORT_ERR')) {
29
+ return new WakeError('WAKE_CANCELLED', 'Wake operation was cancelled', { cause: error })
30
+ }
31
+ if (error && error.code === 'WAKE_UNSUPPORTED_PLATFORM') {
32
+ return wakeError(error, error.cause)
33
+ }
34
+ const message = String(error && error.message ? error.message : error)
35
+ const marker = 'WAKE_ERROR_JSON:'
36
+ const index = message.indexOf(marker)
37
+ if (index !== -1) {
38
+ try {
39
+ return wakeError(JSON.parse(message.slice(index + marker.length)), error)
40
+ } catch {
41
+ // Fall through to the stable internal error.
42
+ }
43
+ }
44
+ return new WakeError('WAKE_INTERNAL', message, { cause: error })
45
+ }
46
+
47
+ function decodeEnvelope(text) {
48
+ let envelope
49
+ try {
50
+ envelope = JSON.parse(text)
51
+ } catch (cause) {
52
+ throw new WakeError('WAKE_INTERNAL', 'Wake returned an invalid native response', { cause })
53
+ }
54
+ if (!envelope.ok) throw wakeError(envelope.error)
55
+ return envelope.value
56
+ }
57
+
58
+ async function invoke(promise) {
59
+ try {
60
+ return decodeEnvelope(await promise)
61
+ } catch (error) {
62
+ if (error instanceof WakeError) throw error
63
+ throw fromNativeError(error)
64
+ }
65
+ }
66
+
67
+ function splitOptions(options) {
68
+ if (options == null) return [{}, undefined]
69
+ if (typeof options !== 'object' || Array.isArray(options)) {
70
+ throw new WakeError('WAKE_CONFIG', 'Wake options must be an object')
71
+ }
72
+ const { signal, ...nativeOptions } = options
73
+ if (signal?.aborted) {
74
+ throw new WakeError('WAKE_CANCELLED', 'Wake operation was cancelled')
75
+ }
76
+ return [nativeOptions, signal]
77
+ }
78
+
79
+ module.exports = {
80
+ WakeError,
81
+ decodeEnvelope,
82
+ fromNativeError,
83
+ invoke,
84
+ splitOptions,
85
+ wakeError,
86
+ }
@@ -0,0 +1,98 @@
1
+ 'use strict'
2
+
3
+ const { loadNative } = require('./loader.cjs')
4
+ const { WakeError, fromNativeError } = require('./errors.cjs')
5
+
6
+ const native = loadNative()
7
+
8
+ class ParsedModule {
9
+ #native
10
+
11
+ constructor(handle) {
12
+ this.#native = handle
13
+ Object.defineProperty(this, '__wakeOpaqueHandle', {
14
+ configurable: false,
15
+ enumerable: true,
16
+ writable: false,
17
+ value: () => {},
18
+ })
19
+ }
20
+
21
+ get disposed() {
22
+ return this.#native.disposed
23
+ }
24
+
25
+ get summary() {
26
+ this.#assertOpen()
27
+ return JSON.parse(this.#native.summaryJson())
28
+ }
29
+
30
+ dispose() {
31
+ this.#native.dispose()
32
+ }
33
+
34
+ _nativeHandle() {
35
+ this.#assertOpen()
36
+ return this.#native
37
+ }
38
+
39
+ #assertOpen() {
40
+ if (this.disposed) {
41
+ throw new WakeError('WAKE_INTERNAL', 'ParsedModule has already been disposed')
42
+ }
43
+ }
44
+
45
+ [Symbol.dispose]() {
46
+ this.dispose()
47
+ }
48
+ }
49
+
50
+ function wrapNative(operation) {
51
+ try {
52
+ return operation()
53
+ } catch (error) {
54
+ throw fromNativeError(error)
55
+ }
56
+ }
57
+
58
+ function tokenize(source, options = {}) {
59
+ void options
60
+ return wrapNative(() => JSON.parse(native.tokenize(String(source))))
61
+ }
62
+
63
+ function parse(source, options = {}) {
64
+ const sourceType = options.sourceType || 'module'
65
+ return wrapNative(() => new ParsedModule(native.parse(String(source), sourceType)))
66
+ }
67
+
68
+ function moduleFrom(value, options) {
69
+ return typeof value === 'string' ? parse(value, options) : value
70
+ }
71
+
72
+ function transform(sourceOrModule, options) {
73
+ const owned = typeof sourceOrModule === 'string'
74
+ const module = moduleFrom(sourceOrModule, options)
75
+ if (!(module instanceof ParsedModule)) {
76
+ throw new TypeError('transform() expects source text or a ParsedModule')
77
+ }
78
+ try {
79
+ return wrapNative(() => JSON.parse(module._nativeHandle().transformJson()))
80
+ } finally {
81
+ if (owned) module.dispose()
82
+ }
83
+ }
84
+
85
+ function analyze(sourceOrModule, options) {
86
+ const owned = typeof sourceOrModule === 'string'
87
+ const module = moduleFrom(sourceOrModule, options)
88
+ if (!(module instanceof ParsedModule)) {
89
+ throw new TypeError('analyze() expects source text or a ParsedModule')
90
+ }
91
+ try {
92
+ return wrapNative(() => JSON.parse(module._nativeHandle().analyzeJson()))
93
+ } finally {
94
+ if (owned) module.dispose()
95
+ }
96
+ }
97
+
98
+ module.exports = { ParsedModule, analyze, parse, tokenize, transform }
@@ -0,0 +1,91 @@
1
+ import type { Diagnostic } from './index.js'
2
+
3
+ export interface ParseOptions {
4
+ sourceType?: 'module' | 'script' | 'commonjs'
5
+ }
6
+
7
+ export interface Token {
8
+ kind: string
9
+ start: number
10
+ end: number
11
+ newlineBefore: boolean
12
+ text: string
13
+ }
14
+
15
+ export interface TokenizeResult {
16
+ tokens: Token[]
17
+ diagnostics: Diagnostic[]
18
+ }
19
+
20
+ export interface ParseSummary {
21
+ sourceBytes: number
22
+ statementCount: number
23
+ dependencies: number
24
+ hasTopLevelAwait: boolean
25
+ diagnostics: Diagnostic[]
26
+ }
27
+
28
+ export interface TransformResult {
29
+ code: string
30
+ diagnostics: Diagnostic[]
31
+ }
32
+
33
+ export interface SemanticScope {
34
+ id: number
35
+ kind: string
36
+ parent: number | null
37
+ bindings: Array<{ name: string; symbol: number }>
38
+ }
39
+
40
+ export interface SemanticSymbol {
41
+ id: number
42
+ name: string
43
+ declarationKind: string
44
+ scope: number
45
+ start: number
46
+ end: number
47
+ }
48
+
49
+ export interface SemanticReference {
50
+ id: number
51
+ name: string
52
+ scope: number
53
+ resolved: number | null
54
+ start: number
55
+ end: number
56
+ }
57
+
58
+ export interface SemanticResult {
59
+ schemaVersion: 'wake.semantic.v1'
60
+ scopes: SemanticScope[]
61
+ symbols: SemanticSymbol[]
62
+ references: SemanticReference[]
63
+ }
64
+
65
+ export class ParsedModule {
66
+ readonly disposed: boolean
67
+ readonly summary: ParseSummary
68
+ dispose(): void
69
+ [Symbol.dispose](): void
70
+ }
71
+
72
+ export function tokenize(source: string, options?: ParseOptions): TokenizeResult
73
+ export function parse(source: string, options?: ParseOptions): ParsedModule
74
+ export function transform(
75
+ sourceOrModule: string | ParsedModule,
76
+ options?: ParseOptions,
77
+ ): TransformResult
78
+ export function analyze(
79
+ sourceOrModule: string | ParsedModule,
80
+ options?: ParseOptions,
81
+ ): SemanticResult
82
+
83
+ declare const experimental: {
84
+ ParsedModule: typeof ParsedModule
85
+ analyze: typeof analyze
86
+ parse: typeof parse
87
+ tokenize: typeof tokenize
88
+ transform: typeof transform
89
+ }
90
+
91
+ export default experimental
@@ -0,0 +1,4 @@
1
+ import api from './experimental.cjs'
2
+
3
+ export const { ParsedModule, analyze, parse, tokenize, transform } = api
4
+ export default api
package/index.cjs ADDED
@@ -0,0 +1,206 @@
1
+ 'use strict'
2
+
3
+ const { EventEmitter } = require('node:events')
4
+ const { loadNative } = require('./loader.cjs')
5
+ const {
6
+ WakeError,
7
+ fromNativeError,
8
+ invoke,
9
+ splitOptions,
10
+ } = require('./errors.cjs')
11
+
12
+ const native = loadNative()
13
+
14
+ function version() {
15
+ return native.version()
16
+ }
17
+
18
+ async function build(options) {
19
+ const [value, signal] = splitOptions(options)
20
+ return invoke(native.build(JSON.stringify(value), signal))
21
+ }
22
+
23
+ async function bundle(options) {
24
+ const [value, signal] = splitOptions(options)
25
+ return invoke(native.bundle(JSON.stringify(value), signal))
26
+ }
27
+
28
+ class BuildContext {
29
+ #native
30
+ #closed = false
31
+
32
+ constructor(handle) {
33
+ this.#native = handle
34
+ }
35
+
36
+ get closed() {
37
+ return this.#closed || this.#native.closed
38
+ }
39
+
40
+ async rebuild(changedPaths = [], options) {
41
+ if (this.closed) {
42
+ throw new WakeError('WAKE_INTERNAL', 'BuildContext has already been closed')
43
+ }
44
+ if (!Array.isArray(changedPaths)) {
45
+ options = changedPaths
46
+ changedPaths = []
47
+ }
48
+ const [, signal] = splitOptions(options)
49
+ return invoke(this.#native.rebuild(changedPaths.map(String), signal))
50
+ }
51
+
52
+ async close() {
53
+ if (this.#closed) return
54
+ this.#closed = true
55
+ await invoke(this.#native.close())
56
+ }
57
+
58
+ async [Symbol.asyncDispose]() {
59
+ await this.close()
60
+ }
61
+ }
62
+
63
+ async function createBuildContext(options) {
64
+ const [value] = splitOptions(options)
65
+ try {
66
+ return new BuildContext(native.createBuildContext(JSON.stringify(value)))
67
+ } catch (error) {
68
+ throw fromNativeError(error)
69
+ }
70
+ }
71
+
72
+ class DevServer extends EventEmitter {
73
+ #native
74
+ #closePromise
75
+ #closed = false
76
+ #closing = false
77
+ #eventTimer
78
+
79
+ constructor(handle) {
80
+ super()
81
+ this.#native = handle
82
+ this.url = handle.url
83
+ const reference = new WeakRef(this)
84
+ const timer = setInterval(() => {
85
+ const server = reference.deref()
86
+ if (server) server.#drainEvents()
87
+ else clearInterval(timer)
88
+ }, 25)
89
+ this.#eventTimer = timer
90
+ timer.unref()
91
+ }
92
+
93
+ #drainEvents() {
94
+ let events
95
+ try {
96
+ events = JSON.parse(this.#native.eventsJson())
97
+ } catch (error) {
98
+ this.emit('diagnostic', {
99
+ severity: 'error',
100
+ code: 'WAKE_INTERNAL',
101
+ message: String(error?.message || error),
102
+ })
103
+ return
104
+ }
105
+ for (const event of events) {
106
+ if (this.#closing && event.type !== 'closed') continue
107
+ if (event.type === 'rebuildStart') {
108
+ this.emit('rebuildStart', event)
109
+ } else if (event.type === 'rebuilt') {
110
+ this.emit('rebuilt', event)
111
+ } else if (event.type === 'diagnostic') {
112
+ this.emit('diagnostic', {
113
+ severity: 'error',
114
+ code: 'WAKE_BUILD',
115
+ message: event.message,
116
+ })
117
+ } else if (event.type === 'closed' && !this.#closed) {
118
+ this.#closed = true
119
+ clearInterval(this.#eventTimer)
120
+ this.emit('closed')
121
+ }
122
+ }
123
+ }
124
+
125
+ async close() {
126
+ if (!this.#closePromise) {
127
+ this.#closing = true
128
+ this.#closePromise = invoke(this.#native.close())
129
+ .then(() => {
130
+ this.#drainEvents()
131
+ if (!this.#closed) {
132
+ this.#closed = true
133
+ clearInterval(this.#eventTimer)
134
+ this.emit('closed')
135
+ }
136
+ })
137
+ }
138
+ return this.#closePromise
139
+ }
140
+
141
+ async waitUntilClosed() {
142
+ if (this.#closed) return
143
+ try {
144
+ await invoke(this.#native.waitUntilClosed())
145
+ this.#drainEvents()
146
+ if (!this.#closed) {
147
+ this.#closed = true
148
+ clearInterval(this.#eventTimer)
149
+ this.emit('closed')
150
+ }
151
+ } catch (error) {
152
+ const diagnostic = {
153
+ severity: 'error',
154
+ code: error.code || 'WAKE_INTERNAL',
155
+ message: error.message,
156
+ }
157
+ this.emit('diagnostic', diagnostic)
158
+ throw error
159
+ }
160
+ }
161
+
162
+ unref() {
163
+ // Wake owns native threads rather than libuv handles. Not awaiting
164
+ // waitUntilClosed() is therefore the unreferenced state.
165
+ return this
166
+ }
167
+
168
+ async [Symbol.asyncDispose]() {
169
+ await this.close()
170
+ }
171
+ }
172
+
173
+ async function startServer(method, options) {
174
+ const [value, signal] = splitOptions(options)
175
+ try {
176
+ return new DevServer(await method(JSON.stringify(value), signal))
177
+ } catch (error) {
178
+ throw fromNativeError(error)
179
+ }
180
+ }
181
+
182
+ function startDevServer(options) {
183
+ return startServer(native.startDevServer, options)
184
+ }
185
+
186
+ async function buildDocs(options) {
187
+ const [value, signal] = splitOptions(options)
188
+ return invoke(native.buildDocs(JSON.stringify(value), signal))
189
+ }
190
+
191
+ function startDocsDevServer(options) {
192
+ return startServer(native.startDocsDevServer, options)
193
+ }
194
+
195
+ module.exports = {
196
+ BuildContext,
197
+ DevServer,
198
+ WakeError,
199
+ build,
200
+ buildDocs,
201
+ bundle,
202
+ createBuildContext,
203
+ startDevServer,
204
+ startDocsDevServer,
205
+ version,
206
+ }
package/index.d.ts ADDED
@@ -0,0 +1,144 @@
1
+ import { EventEmitter } from 'node:events'
2
+
3
+ export type WakeErrorCode =
4
+ | 'WAKE_CONFIG'
5
+ | 'WAKE_PARSE'
6
+ | 'WAKE_BUILD'
7
+ | 'WAKE_IO'
8
+ | 'WAKE_CANCELLED'
9
+ | 'WAKE_UNSUPPORTED_PLATFORM'
10
+ | 'WAKE_INTERNAL'
11
+
12
+ export interface Diagnostic {
13
+ severity: 'error' | 'warning' | 'note' | 'help'
14
+ code?: string
15
+ message: string
16
+ start?: number
17
+ end?: number
18
+ notes?: string[]
19
+ }
20
+
21
+ export class WakeError extends Error {
22
+ readonly code: WakeErrorCode
23
+ readonly path?: string
24
+ readonly diagnostics?: Diagnostic[]
25
+ override readonly cause?: unknown
26
+ }
27
+
28
+ export interface ProjectOptions {
29
+ cwd?: string
30
+ configPath?: string
31
+ signal?: AbortSignal
32
+ }
33
+
34
+ export interface BuildOptions extends ProjectOptions {
35
+ entry?: string
36
+ outdir?: string
37
+ cache?: boolean
38
+ sourceMap?: boolean
39
+ }
40
+
41
+ export interface OutputFile {
42
+ path: string
43
+ kind: 'chunk' | 'css' | 'asset' | 'html'
44
+ bytes: number
45
+ }
46
+
47
+ export interface BuildResult {
48
+ success: true
49
+ moduleCount: number
50
+ durationMs: number
51
+ outputDir?: string
52
+ code?: string
53
+ files: OutputFile[]
54
+ diagnostics: Diagnostic[]
55
+ }
56
+
57
+ export interface BundleResult extends BuildResult {
58
+ code: string
59
+ outputDir?: undefined
60
+ }
61
+
62
+ export interface DocsRoute {
63
+ id: string
64
+ file: string
65
+ title: string
66
+ description: string
67
+ group: string
68
+ groupOrder: number
69
+ order: number
70
+ slug: string
71
+ status: string
72
+ draft: boolean
73
+ headings: Array<{ depth: number; title: string; id: string }>
74
+ }
75
+
76
+ export interface DocsBuildOptions extends ProjectOptions {
77
+ outdir?: string
78
+ basePath?: string
79
+ }
80
+
81
+ export interface DocsBuildResult extends BuildResult {
82
+ routes: DocsRoute[]
83
+ }
84
+
85
+ export interface DevServerOptions extends ProjectOptions {
86
+ entry?: string
87
+ host?: string
88
+ port?: number
89
+ open?: boolean
90
+ }
91
+
92
+ export interface DevServerRebuildStartEvent {
93
+ type: 'rebuildStart'
94
+ changedPaths: string[]
95
+ }
96
+
97
+ export interface DevServerRebuiltEvent {
98
+ type: 'rebuilt'
99
+ modules: number
100
+ durationMs: number
101
+ }
102
+
103
+ export class BuildContext {
104
+ readonly closed: boolean
105
+ rebuild(changedPaths?: string[], options?: { signal?: AbortSignal }): Promise<BuildResult>
106
+ rebuild(options?: { signal?: AbortSignal }): Promise<BuildResult>
107
+ close(): Promise<void>
108
+ [Symbol.asyncDispose](): Promise<void>
109
+ }
110
+
111
+ export class DevServer extends EventEmitter {
112
+ readonly url: string
113
+ close(): Promise<void>
114
+ waitUntilClosed(): Promise<void>
115
+ unref(): this
116
+ [Symbol.asyncDispose](): Promise<void>
117
+ on(event: 'rebuildStart', listener: (event: DevServerRebuildStartEvent) => void): this
118
+ on(event: 'rebuilt', listener: (event: DevServerRebuiltEvent) => void): this
119
+ on(event: 'diagnostic', listener: (diagnostic: Diagnostic) => void): this
120
+ on(event: 'closed', listener: () => void): this
121
+ }
122
+
123
+ export function version(): string
124
+ export function bundle(options: BuildOptions): Promise<BundleResult>
125
+ export function build(options?: BuildOptions): Promise<BuildResult>
126
+ export function createBuildContext(options?: BuildOptions): Promise<BuildContext>
127
+ export function startDevServer(options?: DevServerOptions): Promise<DevServer>
128
+ export function buildDocs(options?: DocsBuildOptions): Promise<DocsBuildResult>
129
+ export function startDocsDevServer(options?: DevServerOptions): Promise<DevServer>
130
+
131
+ declare const wake: {
132
+ BuildContext: typeof BuildContext
133
+ DevServer: typeof DevServer
134
+ WakeError: typeof WakeError
135
+ build: typeof build
136
+ buildDocs: typeof buildDocs
137
+ bundle: typeof bundle
138
+ createBuildContext: typeof createBuildContext
139
+ startDevServer: typeof startDevServer
140
+ startDocsDevServer: typeof startDocsDevServer
141
+ version: typeof version
142
+ }
143
+
144
+ export default wake
package/index.mjs ADDED
@@ -0,0 +1,16 @@
1
+ import api from './index.cjs'
2
+
3
+ export const {
4
+ BuildContext,
5
+ DevServer,
6
+ WakeError,
7
+ build,
8
+ buildDocs,
9
+ bundle,
10
+ createBuildContext,
11
+ startDevServer,
12
+ startDocsDevServer,
13
+ version,
14
+ } = api
15
+
16
+ export default api
package/loader.cjs ADDED
@@ -0,0 +1,55 @@
1
+ 'use strict'
2
+
3
+ const path = require('node:path')
4
+
5
+ const targets = {
6
+ 'win32-x64': '@crab-dev/wake-win32-x64-msvc',
7
+ 'linux-x64': '@crab-dev/wake-linux-x64-gnu',
8
+ 'linux-arm64': '@crab-dev/wake-linux-arm64-gnu',
9
+ 'darwin-x64': '@crab-dev/wake-darwin-x64',
10
+ 'darwin-arm64': '@crab-dev/wake-darwin-arm64',
11
+ }
12
+
13
+ function unsupported(message, cause) {
14
+ const error = new Error(message, cause ? { cause } : undefined)
15
+ error.name = 'WakeError'
16
+ error.code = 'WAKE_UNSUPPORTED_PLATFORM'
17
+ return error
18
+ }
19
+
20
+ function loadNative() {
21
+ if (process.env.WAKE_NATIVE_PATH) {
22
+ return require(path.resolve(process.env.WAKE_NATIVE_PATH))
23
+ }
24
+
25
+ const key = `${process.platform}-${process.arch}`
26
+ if (
27
+ process.platform === 'linux' &&
28
+ !process.report?.getReport?.().header?.glibcVersionRuntime
29
+ ) {
30
+ throw unsupported(
31
+ `Wake does not provide a native binary for ${process.platform}/${process.arch} with musl. ` +
32
+ 'Install on a glibc 2.28 or newer system.',
33
+ )
34
+ }
35
+ const packageName = targets[key]
36
+ if (!packageName) {
37
+ throw unsupported(
38
+ `Wake does not provide a native binary for ${process.platform}/${process.arch}. ` +
39
+ 'Supported targets: Windows x64, Linux glibc x64/arm64, and macOS x64/arm64.',
40
+ )
41
+ }
42
+
43
+ try {
44
+ return require(packageName)
45
+ } catch (cause) {
46
+ throw unsupported(
47
+ `Unable to load ${packageName} for ${process.platform}/${process.arch}. ` +
48
+ `Optional dependencies may have been omitted; ` +
49
+ 'reinstall @crab-dev/wake without --omit=optional and verify that your platform is supported.',
50
+ cause,
51
+ )
52
+ }
53
+ }
54
+
55
+ module.exports = { loadNative }
package/package.json ADDED
@@ -0,0 +1,58 @@
1
+ {
2
+ "name": "@crab-dev/wake",
3
+ "version": "0.1.2",
4
+ "description": "Wake native web build tools for Node.js",
5
+ "license": "MIT OR Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/hotlif/wake.git"
9
+ },
10
+ "type": "module",
11
+ "main": "./index.cjs",
12
+ "module": "./index.mjs",
13
+ "types": "./index.d.ts",
14
+ "exports": {
15
+ ".": {
16
+ "types": "./index.d.ts",
17
+ "import": "./index.mjs",
18
+ "require": "./index.cjs"
19
+ },
20
+ "./experimental": {
21
+ "types": "./experimental.d.ts",
22
+ "import": "./experimental.mjs",
23
+ "require": "./experimental.cjs"
24
+ },
25
+ "./package.json": "./package.json"
26
+ },
27
+ "bin": {
28
+ "wake": "./bin/wake.mjs"
29
+ },
30
+ "napi": {
31
+ "binaryName": "wake"
32
+ },
33
+ "files": [
34
+ "bin",
35
+ "*.cjs",
36
+ "*.mjs",
37
+ "index.d.ts",
38
+ "experimental.d.ts",
39
+ "README.md",
40
+ "CHANGELOG.md",
41
+ "LICENSE-MIT",
42
+ "LICENSE-APACHE"
43
+ ],
44
+ "engines": {
45
+ "node": ">=22.14 <27"
46
+ },
47
+ "optionalDependencies": {
48
+ "@crab-dev/wake-win32-x64-msvc": "0.1.2",
49
+ "@crab-dev/wake-linux-x64-gnu": "0.1.2",
50
+ "@crab-dev/wake-linux-arm64-gnu": "0.1.2",
51
+ "@crab-dev/wake-darwin-x64": "0.1.2",
52
+ "@crab-dev/wake-darwin-arm64": "0.1.2"
53
+ },
54
+ "publishConfig": {
55
+ "access": "public",
56
+ "provenance": true
57
+ }
58
+ }