nuxt-ai-ready 2.5.1 → 2.5.3
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/dist/cli.mjs +2 -0
- package/dist/module.json +1 -1
- package/dist/runtime/server/db/drizzle/queries.js +0 -1
- package/dist/runtime/server/db/queries.d.ts +2 -0
- package/dist/runtime/server/db/queries.js +6 -1
- package/dist/runtime/server/db/seed.d.ts +2 -2
- package/dist/runtime/server/middleware/markdown.js +3 -3
- package/dist/runtime/server/routes/__ai-ready/reindex.post.js +2 -0
- package/dist/runtime/server/utils/batchIndex.js +4 -2
- package/dist/runtime/server/utils/checkStale.d.ts +1 -1
- package/dist/runtime/server/utils/checkStale.js +1 -1
- package/dist/runtime/server/utils/indexPage.d.ts +8 -1
- package/dist/runtime/server/utils/indexPage.js +13 -5
- package/dist/runtime/server/utils/negotiation-response.d.ts +1 -1
- package/dist/runtime/server/utils/negotiation-response.js +17 -2
- package/node_modules/mdream/node_modules/@emnapi/core/node_modules/@emnapi/wasi-threads/LICENSE +21 -0
- package/node_modules/mdream/node_modules/@emnapi/core/node_modules/@emnapi/wasi-threads/README.md +203 -0
- package/node_modules/mdream/node_modules/@emnapi/core/node_modules/@emnapi/wasi-threads/dist/wasi-threads.d.ts +236 -0
- package/node_modules/mdream/node_modules/@emnapi/core/node_modules/@emnapi/wasi-threads/dist/wasi-threads.js +1086 -0
- package/node_modules/mdream/node_modules/@emnapi/core/node_modules/@emnapi/wasi-threads/package.json +35 -0
- package/node_modules/mdream/node_modules/@emnapi/core/node_modules/@emnapi/wasi-threads/rollup.config.js +6 -0
- package/node_modules/mdream/node_modules/@emnapi/wasi-threads/dist/wasi-threads.d.ts +4 -0
- package/node_modules/mdream/node_modules/@emnapi/wasi-threads/dist/wasi-threads.js +48 -16
- package/node_modules/mdream/node_modules/@emnapi/wasi-threads/package.json +1 -1
- package/node_modules/mdream/node_modules/@napi-rs/wasm-runtime/dist/fs.js +3339 -4021
- package/node_modules/mdream/node_modules/@napi-rs/wasm-runtime/package.json +1 -1
- package/package.json +1 -1
package/dist/cli.mjs
CHANGED
|
@@ -320,6 +320,8 @@ const main = defineCommand({
|
|
|
320
320
|
}
|
|
321
321
|
} else if (res.skipped) {
|
|
322
322
|
consola.info(`Skipped: ${colors.yellow(res.route)} (still fresh)`);
|
|
323
|
+
} else if (res.gone) {
|
|
324
|
+
consola.success(`Removed: ${colors.green(res.route)} (HTTP 410)`);
|
|
323
325
|
} else {
|
|
324
326
|
throw new Error(`Failed to reindex ${res.route ?? args.route}${res.error ? `: ${res.error}` : ""}`);
|
|
325
327
|
}
|
package/dist/module.json
CHANGED
|
@@ -706,7 +706,6 @@ export async function seedRoutes(event, routes, options = {}) {
|
|
|
706
706
|
indexed = CASE WHEN ai_ready_pages.is_error = 1 THEN 0 ELSE ai_ready_pages.indexed END
|
|
707
707
|
WHERE ai_ready_pages.last_seen_at IS NULL
|
|
708
708
|
OR ai_ready_pages.last_seen_at < excluded.last_seen_at - ${refreshWindowMs}
|
|
709
|
-
OR ai_ready_pages.is_error = 1
|
|
710
709
|
OR ai_ready_pages.locale IS DISTINCT FROM excluded.locale
|
|
711
710
|
`,
|
|
712
711
|
params
|
|
@@ -147,6 +147,8 @@ export declare function seedRoutes(event: H3Event | undefined, routes: Array<str
|
|
|
147
147
|
locale?: string;
|
|
148
148
|
url?: string;
|
|
149
149
|
}>, options?: SeedRoutesOptions): Promise<number>;
|
|
150
|
+
/** Remove a page after its route returns HTTP 410. */
|
|
151
|
+
export declare function prunePage(event: H3Event | undefined, route: string): Promise<void>;
|
|
150
152
|
/**
|
|
151
153
|
* Prune routes not seen in sitemap for longer than threshold
|
|
152
154
|
* Only prunes routes with source='runtime' (never prerendered pages)
|
|
@@ -403,7 +403,6 @@ export async function seedRoutes(event, routes, options = {}) {
|
|
|
403
403
|
indexed = CASE WHEN ai_ready_pages.is_error = 1 THEN 0 ELSE ai_ready_pages.indexed END
|
|
404
404
|
WHERE ai_ready_pages.last_seen_at IS NULL
|
|
405
405
|
OR ai_ready_pages.last_seen_at < excluded.last_seen_at - ${refreshWindowMs}
|
|
406
|
-
OR ai_ready_pages.is_error = 1
|
|
407
406
|
OR ai_ready_pages.locale IS DISTINCT FROM excluded.locale
|
|
408
407
|
`,
|
|
409
408
|
params
|
|
@@ -412,6 +411,12 @@ export async function seedRoutes(event, routes, options = {}) {
|
|
|
412
411
|
await db.batch(stmts);
|
|
413
412
|
return byRoute.size;
|
|
414
413
|
}
|
|
414
|
+
export async function prunePage(event, route) {
|
|
415
|
+
const db = await getDb(event);
|
|
416
|
+
if (!db)
|
|
417
|
+
return;
|
|
418
|
+
await db.exec("DELETE FROM ai_ready_pages WHERE route = ?", [normalizeRoute(route)]);
|
|
419
|
+
}
|
|
415
420
|
export async function pruneStaleRoutes(event, staleThresholdSeconds, protectedSince, refreshWindowMs = SEED_REFRESH_WINDOW_MS) {
|
|
416
421
|
const db = await getDb(event);
|
|
417
422
|
if (!db)
|
|
@@ -24,8 +24,8 @@ export declare const SEED_REFRESH_WINDOW_MS: number;
|
|
|
24
24
|
export declare function resolveSeedRefreshWindowMs(pruneTtlSeconds: number): number;
|
|
25
25
|
export interface SeedRoutesOptions {
|
|
26
26
|
/**
|
|
27
|
-
* An existing row is rewritten
|
|
28
|
-
*
|
|
27
|
+
* An existing row is rewritten when its `last_seen_at` is older than this
|
|
28
|
+
* or its locale changed. Error rows retry after this interval.
|
|
29
29
|
* @default SEED_REFRESH_WINDOW_MS
|
|
30
30
|
*/
|
|
31
31
|
refreshWindowMs?: number;
|
|
@@ -128,13 +128,13 @@ ${contentPage.markdown}`);
|
|
|
128
128
|
if (!response.ok && response.status !== 404)
|
|
129
129
|
return response;
|
|
130
130
|
if (response.status === 404) {
|
|
131
|
-
setMarkdownHeaders(event, ctx);
|
|
131
|
+
setMarkdownHeaders(event, ctx, response.headers);
|
|
132
132
|
setResponseStatus(event, 404);
|
|
133
133
|
return notFoundMarkdown(ctx, canonicalUrl, buildFrontmatter);
|
|
134
134
|
}
|
|
135
135
|
const contentType = response.headers.get("content-type") || "";
|
|
136
136
|
if (!contentType.includes("text/html")) {
|
|
137
|
-
setMarkdownHeaders(event, ctx);
|
|
137
|
+
setMarkdownHeaders(event, ctx, response.headers);
|
|
138
138
|
setResponseStatus(event, 404);
|
|
139
139
|
return notFoundMarkdown(ctx, canonicalUrl, buildFrontmatter);
|
|
140
140
|
}
|
|
@@ -169,6 +169,6 @@ ${contentPage.markdown}`);
|
|
|
169
169
|
additionalFrontmatter
|
|
170
170
|
}
|
|
171
171
|
);
|
|
172
|
-
setMarkdownHeaders(event, ctx);
|
|
172
|
+
setMarkdownHeaders(event, ctx, response.headers);
|
|
173
173
|
return finalizeMarkdown(result.markdown);
|
|
174
174
|
});
|
|
@@ -10,6 +10,8 @@ export default eventHandler(async (event) => {
|
|
|
10
10
|
}
|
|
11
11
|
const force = query.force !== "false" && query.force !== "0";
|
|
12
12
|
const result = await indexPageByRoute(route, event, { force });
|
|
13
|
+
if (result.gone)
|
|
14
|
+
return { route, indexed: false, gone: true };
|
|
13
15
|
if (!result.success) {
|
|
14
16
|
setResponseStatus(event, 502);
|
|
15
17
|
return { route, indexed: false, error: result.error ?? `Failed to index ${route}` };
|
|
@@ -36,12 +36,14 @@ export async function batchIndexPages(event, options = {}) {
|
|
|
36
36
|
markFailedAsError: true,
|
|
37
37
|
force: true
|
|
38
38
|
});
|
|
39
|
-
return { route: page.route,
|
|
39
|
+
return { route: page.route, result };
|
|
40
40
|
})
|
|
41
41
|
);
|
|
42
42
|
for (const result of results) {
|
|
43
43
|
processed++;
|
|
44
|
-
if (result.
|
|
44
|
+
if (result.result.gone) {
|
|
45
|
+
logger.debug(`[batchIndex] Pruned gone route: ${result.route}`);
|
|
46
|
+
} else if (result.result.success) {
|
|
45
47
|
indexed++;
|
|
46
48
|
logger.debug(`[batchIndex] Indexed: ${result.route}`);
|
|
47
49
|
} else {
|
|
@@ -21,7 +21,7 @@ export declare const STALE_CHECK_INTERVAL_MS: number;
|
|
|
21
21
|
/**
|
|
22
22
|
* Check if data is stale and handle restore/mark-pending
|
|
23
23
|
* Called at start of cron - handles:
|
|
24
|
-
* 1. Empty DB → restore from dump
|
|
24
|
+
* 1. Empty DB with a different build ID → restore from dump
|
|
25
25
|
* 2. Build ID changed → compare hashes, only mark changed pages pending, add new pages from dump
|
|
26
26
|
* Skips HTTP fetch if checked within 5 minutes and DB is populated
|
|
27
27
|
*/
|
|
@@ -78,7 +78,7 @@ export async function checkAndHandleStale(event) {
|
|
|
78
78
|
logger.info("[stale-check] No build metadata found, skipping stale check");
|
|
79
79
|
return { action: "none", dbCount, reason: "no_dump_metadata" };
|
|
80
80
|
}
|
|
81
|
-
if (dbCount === 0) {
|
|
81
|
+
if (dbCount === 0 && storedBuildId !== meta.buildId) {
|
|
82
82
|
if (debug)
|
|
83
83
|
logger.info("[stale-check] DB empty, restoring from dump...");
|
|
84
84
|
const rows = await fetchDump(event);
|
|
@@ -9,7 +9,7 @@ export interface IndexPageOptions {
|
|
|
9
9
|
/** Mark failed fetches as errors in DB to prevent retry loops */
|
|
10
10
|
markFailedAsError?: boolean;
|
|
11
11
|
}
|
|
12
|
-
|
|
12
|
+
interface IndexedPageResult {
|
|
13
13
|
success: boolean;
|
|
14
14
|
/** True if page was already fresh and skipped */
|
|
15
15
|
skipped?: boolean;
|
|
@@ -31,6 +31,12 @@ export interface IndexPageResult {
|
|
|
31
31
|
/** Error message if failed */
|
|
32
32
|
error?: string;
|
|
33
33
|
}
|
|
34
|
+
export type IndexPageResult = IndexedPageResult & ({
|
|
35
|
+
success: false;
|
|
36
|
+
gone: true;
|
|
37
|
+
} | {
|
|
38
|
+
gone?: never;
|
|
39
|
+
});
|
|
34
40
|
/**
|
|
35
41
|
* Manually index a page's HTML content into database
|
|
36
42
|
* Use this from custom plugins or API routes to trigger indexing
|
|
@@ -41,3 +47,4 @@ export declare function indexPage(route: string, html: string, options?: IndexPa
|
|
|
41
47
|
* Convenience wrapper around indexPage that handles fetching
|
|
42
48
|
*/
|
|
43
49
|
export declare function indexPageByRoute(route: string, event: H3Event | undefined, options?: IndexPageOptions): Promise<IndexPageResult>;
|
|
50
|
+
export {};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { fetchWithEvent, useNitroApp, useRuntimeConfig } from "#nuxtseo/nitro";
|
|
2
|
-
import { getPageIndexState, upsertPage } from "../db/queries.js";
|
|
2
|
+
import { getPageIndexState, prunePage, upsertPage } from "../db/queries.js";
|
|
3
3
|
import { computeContentHash } from "../db/shared.js";
|
|
4
4
|
import { logger } from "../logger.js";
|
|
5
5
|
import { convertHtmlToMarkdown } from "../utils.js";
|
|
@@ -79,18 +79,26 @@ export async function indexPage(route, html, options = {}, event) {
|
|
|
79
79
|
}
|
|
80
80
|
export async function indexPageByRoute(route, event, options = {}) {
|
|
81
81
|
logger.debug(`[indexPageByRoute] Fetching HTML for ${route} (timeout: 10000ms)`);
|
|
82
|
-
const
|
|
82
|
+
const fetched = await (event ? fetchWithEvent(event, route, {
|
|
83
83
|
headers: { accept: "text/html", [INTERNAL_HEADER]: "1" },
|
|
84
84
|
timeout: 1e4
|
|
85
85
|
}) : globalThis.$fetch(route, {
|
|
86
86
|
headers: { accept: "text/html", [INTERNAL_HEADER]: "1" },
|
|
87
87
|
timeout: 1e4
|
|
88
88
|
// 10s timeout per page (must fit within CF worker limit)
|
|
89
|
-
})).catch((err) => {
|
|
89
|
+
})).then((html2) => ({ _tag: "Html", html: html2 })).catch((err) => {
|
|
90
|
+
const status = err.status ?? err.statusCode ?? err.response?.status;
|
|
91
|
+
if (status === 410)
|
|
92
|
+
return { _tag: "Gone" };
|
|
90
93
|
logger.warn(`[indexPageByRoute] Failed to fetch ${route}:`, err.message);
|
|
91
|
-
return
|
|
94
|
+
return { _tag: "Failed" };
|
|
92
95
|
});
|
|
93
|
-
if (
|
|
96
|
+
if (fetched._tag === "Gone") {
|
|
97
|
+
await prunePage(event, route);
|
|
98
|
+
return { success: false, gone: true };
|
|
99
|
+
}
|
|
100
|
+
const html = fetched._tag === "Html" ? fetched.html : null;
|
|
101
|
+
if (typeof html === "string" && html) {
|
|
94
102
|
logger.debug(`[indexPageByRoute] Fetched ${route} (${html.length} bytes)`);
|
|
95
103
|
}
|
|
96
104
|
if (!html || typeof html !== "string") {
|
|
@@ -17,7 +17,7 @@ type NegotiationResponse = Awaited<ReturnType<typeof sendRedirect>> | undefined;
|
|
|
17
17
|
export declare function setLinkHeader(event: H3Event, ctx: NegotiationContext, variant: 'html' | 'markdown'): void;
|
|
18
18
|
export declare function setStatusAwareHeader(event: H3Event, ctx: NegotiationContext, variant: 'html' | 'markdown'): void;
|
|
19
19
|
export declare function setUncacheableHeaders(event: H3Event): void;
|
|
20
|
-
export declare function setMarkdownHeaders(event: H3Event, ctx: NegotiationContext): void;
|
|
20
|
+
export declare function setMarkdownHeaders(event: H3Event, ctx: NegotiationContext, sourceHeaders?: Headers): void;
|
|
21
21
|
/**
|
|
22
22
|
* Site config is set up by a Nitro middleware. The early negotiation handler
|
|
23
23
|
* runs in front of that middleware, so it must run the setup itself before it
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createNitroRouteRuleMatcher } from "nuxtseo-shared/server";
|
|
2
2
|
import { localAgentSkillArtifacts } from "#ai-ready-virtual/agent-skills.mjs";
|
|
3
|
-
import { appendHeader, createError, getRequestHost, getResponseHeader, sendRedirect, setHeader } from "#nuxtseo/h3";
|
|
3
|
+
import { appendHeader, createError, getHeader, getRequestHost, getResponseHeader, sendRedirect, setHeader } from "#nuxtseo/h3";
|
|
4
4
|
import { useRuntimeConfig } from "#nuxtseo/nitro";
|
|
5
5
|
import { withSiteUrl } from "#site-config/server/composables/utils";
|
|
6
6
|
import initSiteConfig from "#site-config/server/middleware/init";
|
|
@@ -42,9 +42,24 @@ export function setUncacheableHeaders(event) {
|
|
|
42
42
|
setHeader(event, header, "no-store");
|
|
43
43
|
}
|
|
44
44
|
}
|
|
45
|
-
export function setMarkdownHeaders(event, ctx) {
|
|
45
|
+
export function setMarkdownHeaders(event, ctx, sourceHeaders) {
|
|
46
46
|
setHeader(event, "content-type", "text/markdown; charset=utf-8");
|
|
47
47
|
setLinkHeader(event, ctx, "markdown");
|
|
48
|
+
const privateResponse = [
|
|
49
|
+
"cache-control",
|
|
50
|
+
"cdn-cache-control",
|
|
51
|
+
"cloudflare-cdn-cache-control",
|
|
52
|
+
"netlify-cdn-cache-control",
|
|
53
|
+
"vercel-cdn-cache-control",
|
|
54
|
+
"surrogate-control"
|
|
55
|
+
].some((header) => {
|
|
56
|
+
const value = `${getResponseHeader(event, header) || ""},${sourceHeaders?.get(header) || ""}`;
|
|
57
|
+
return /(?:^|,)\s*(?:private|no-store|no-cache)\s*(?:,|=|$)/i.test(value);
|
|
58
|
+
});
|
|
59
|
+
if (getHeader(event, "cookie") || getHeader(event, "authorization") || getResponseHeader(event, "set-cookie") || sourceHeaders?.has("set-cookie") || privateResponse) {
|
|
60
|
+
setUncacheableHeaders(event);
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
48
63
|
const cacheHeaders = ctx.config.markdownCacheHeaders;
|
|
49
64
|
if (cacheHeaders) {
|
|
50
65
|
const { maxAge, swr } = cacheHeaders;
|
package/node_modules/mdream/node_modules/@emnapi/core/node_modules/@emnapi/wasi-threads/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2021-present Toyobayashi
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/node_modules/mdream/node_modules/@emnapi/core/node_modules/@emnapi/wasi-threads/README.md
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
# @emnapi/wasi-threads
|
|
2
|
+
|
|
3
|
+
This package makes [wasi-threads proposal](https://github.com/WebAssembly/wasi-threads) based WASI modules work in Node.js and browser.
|
|
4
|
+
|
|
5
|
+
## Quick Start
|
|
6
|
+
|
|
7
|
+
`index.html`
|
|
8
|
+
|
|
9
|
+
```html
|
|
10
|
+
<script src="./node_modules/@tybys/wasm-util/dist/wasm-util.js"></script>
|
|
11
|
+
<script src="./node_modules/@emnapi/wasi-threads/dist/wasi-threads.js"></script>
|
|
12
|
+
<script src="./index.js"></script>
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
If your application will block browser main thread (for example `pthread_join`), please run it in worker instead.
|
|
16
|
+
|
|
17
|
+
```html
|
|
18
|
+
<script>
|
|
19
|
+
// pthread_join (Atomics.wait) cannot be called in browser main thread
|
|
20
|
+
new Worker('./index.js')
|
|
21
|
+
</script>
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
`index.js`
|
|
25
|
+
|
|
26
|
+
```js
|
|
27
|
+
const ENVIRONMENT_IS_NODE =
|
|
28
|
+
typeof process === 'object' && process !== null &&
|
|
29
|
+
typeof process.versions === 'object' && process.versions !== null &&
|
|
30
|
+
typeof process.versions.node === 'string';
|
|
31
|
+
|
|
32
|
+
(function (main) {
|
|
33
|
+
if (ENVIRONMENT_IS_NODE) {
|
|
34
|
+
main(require)
|
|
35
|
+
} else {
|
|
36
|
+
if (typeof importScripts === 'function') {
|
|
37
|
+
importScripts('./node_modules/@tybys/wasm-util/dist/wasm-util.js')
|
|
38
|
+
importScripts('./node_modules/@emnapi/wasi-threads/dist/wasi-threads.js')
|
|
39
|
+
}
|
|
40
|
+
const nodeWasi = { WASI: globalThis.wasmUtil.WASI }
|
|
41
|
+
const nodeWorkerThreads = {
|
|
42
|
+
Worker: globalThis.Worker
|
|
43
|
+
}
|
|
44
|
+
const _require = function (request) {
|
|
45
|
+
if (request === 'node:wasi' || request === 'wasi') return nodeWasi
|
|
46
|
+
if (request === 'node:worker_threads' || request === 'worker_threads') return nodeWorkerThreads
|
|
47
|
+
if (request === '@emnapi/wasi-threads') return globalThis.wasiThreads
|
|
48
|
+
throw new Error('Can not find module: ' + request)
|
|
49
|
+
}
|
|
50
|
+
main(_require)
|
|
51
|
+
}
|
|
52
|
+
})(async function (require) {
|
|
53
|
+
const { WASI } = require('wasi')
|
|
54
|
+
const { Worker } = require('worker_threads')
|
|
55
|
+
const { WASIThreads } = require('@emnapi/wasi-threads')
|
|
56
|
+
|
|
57
|
+
const wasi = new WASI({
|
|
58
|
+
version: 'preview1'
|
|
59
|
+
})
|
|
60
|
+
const wasiThreads = new WASIThreads({
|
|
61
|
+
wasi,
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* avoid Atomics.wait() deadlock during thread creation in browser
|
|
65
|
+
* see https://emscripten.org/docs/tools_reference/settings_reference.html#pthread-pool-size
|
|
66
|
+
*/
|
|
67
|
+
reuseWorker: ENVIRONMENT_IS_NODE
|
|
68
|
+
? false
|
|
69
|
+
: {
|
|
70
|
+
size: 4 /** greater than actual needs (2) */,
|
|
71
|
+
strict: true
|
|
72
|
+
},
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Synchronous thread creation
|
|
76
|
+
* pthread_create will not return until thread worker actually starts
|
|
77
|
+
*/
|
|
78
|
+
waitThreadStart: typeof window === 'undefined' ? 1000 : false,
|
|
79
|
+
|
|
80
|
+
onCreateWorker: () => {
|
|
81
|
+
return new Worker('./worker.js', {
|
|
82
|
+
execArgv: ['--experimental-wasi-unstable-preview1']
|
|
83
|
+
})
|
|
84
|
+
}
|
|
85
|
+
})
|
|
86
|
+
const memory = new WebAssembly.Memory({
|
|
87
|
+
initial: 16777216 / 65536,
|
|
88
|
+
maximum: 2147483648 / 65536,
|
|
89
|
+
shared: true
|
|
90
|
+
})
|
|
91
|
+
let input
|
|
92
|
+
const file = 'path/to/your/wasi-module.wasm'
|
|
93
|
+
try {
|
|
94
|
+
input = require('fs').readFileSync(require('path').join(__dirname, file))
|
|
95
|
+
} catch (err) {
|
|
96
|
+
const response = await fetch(file)
|
|
97
|
+
input = await response.arrayBuffer()
|
|
98
|
+
}
|
|
99
|
+
let { module, instance } = await WebAssembly.instantiate(input, {
|
|
100
|
+
env: { memory },
|
|
101
|
+
wasi_snapshot_preview1: wasi.wasiImport,
|
|
102
|
+
...wasiThreads.getImportObject()
|
|
103
|
+
})
|
|
104
|
+
|
|
105
|
+
wasiThreads.setup(instance, module, memory)
|
|
106
|
+
await wasiThreads.preloadWorkers()
|
|
107
|
+
|
|
108
|
+
if (typeof instance.exports._start === 'function') {
|
|
109
|
+
return wasi.start(instance)
|
|
110
|
+
} else {
|
|
111
|
+
wasi.initialize(instance)
|
|
112
|
+
// instance.exports.exported_wasm_function()
|
|
113
|
+
}
|
|
114
|
+
})
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
`worker.js`
|
|
118
|
+
|
|
119
|
+
```js
|
|
120
|
+
(function (main) {
|
|
121
|
+
const ENVIRONMENT_IS_NODE =
|
|
122
|
+
typeof process === 'object' && process !== null &&
|
|
123
|
+
typeof process.versions === 'object' && process.versions !== null &&
|
|
124
|
+
typeof process.versions.node === 'string'
|
|
125
|
+
|
|
126
|
+
if (ENVIRONMENT_IS_NODE) {
|
|
127
|
+
const _require = function (request) {
|
|
128
|
+
return require(request)
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const _init = function () {
|
|
132
|
+
const nodeWorkerThreads = require('worker_threads')
|
|
133
|
+
const parentPort = nodeWorkerThreads.parentPort
|
|
134
|
+
|
|
135
|
+
parentPort.on('message', (data) => {
|
|
136
|
+
globalThis.onmessage({ data })
|
|
137
|
+
})
|
|
138
|
+
|
|
139
|
+
Object.assign(globalThis, {
|
|
140
|
+
self: globalThis,
|
|
141
|
+
require,
|
|
142
|
+
Worker: nodeWorkerThreads.Worker,
|
|
143
|
+
importScripts: function (f) {
|
|
144
|
+
(0, eval)(require('fs').readFileSync(f, 'utf8') + '//# sourceURL=' + f)
|
|
145
|
+
},
|
|
146
|
+
postMessage: function (msg) {
|
|
147
|
+
parentPort.postMessage(msg)
|
|
148
|
+
}
|
|
149
|
+
})
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
main(_require, _init)
|
|
153
|
+
} else {
|
|
154
|
+
importScripts('./node_modules/@tybys/wasm-util/dist/wasm-util.js')
|
|
155
|
+
importScripts('./node_modules/@emnapi/wasi-threads/dist/wasi-threads.js')
|
|
156
|
+
|
|
157
|
+
const nodeWasi = { WASI: globalThis.wasmUtil.WASI }
|
|
158
|
+
const _require = function (request) {
|
|
159
|
+
if (request === '@emnapi/wasi-threads') return globalThis.wasiThreads
|
|
160
|
+
if (request === 'node:wasi' || request === 'wasi') return nodeWasi
|
|
161
|
+
throw new Error('Can not find module: ' + request)
|
|
162
|
+
}
|
|
163
|
+
const _init = function () {}
|
|
164
|
+
main(_require, _init)
|
|
165
|
+
}
|
|
166
|
+
})(function main (require, init) {
|
|
167
|
+
init()
|
|
168
|
+
|
|
169
|
+
const { WASI } = require('wasi')
|
|
170
|
+
const { ThreadMessageHandler, WASIThreads } = require('@emnapi/wasi-threads')
|
|
171
|
+
|
|
172
|
+
const handler = new ThreadMessageHandler({
|
|
173
|
+
async onLoad ({ wasmModule, wasmMemory }) {
|
|
174
|
+
const wasi = new WASI({
|
|
175
|
+
version: 'preview1'
|
|
176
|
+
})
|
|
177
|
+
|
|
178
|
+
const wasiThreads = new WASIThreads({
|
|
179
|
+
wasi,
|
|
180
|
+
childThread: true
|
|
181
|
+
})
|
|
182
|
+
|
|
183
|
+
const originalInstance = await WebAssembly.instantiate(wasmModule, {
|
|
184
|
+
env: {
|
|
185
|
+
memory: wasmMemory,
|
|
186
|
+
},
|
|
187
|
+
wasi_snapshot_preview1: wasi.wasiImport,
|
|
188
|
+
...wasiThreads.getImportObject()
|
|
189
|
+
})
|
|
190
|
+
|
|
191
|
+
// must call `initialize` instead of `start` in child thread
|
|
192
|
+
const instance = wasiThreads.initialize(originalInstance, wasmModule, wasmMemory)
|
|
193
|
+
|
|
194
|
+
return { module: wasmModule, instance }
|
|
195
|
+
}
|
|
196
|
+
})
|
|
197
|
+
|
|
198
|
+
globalThis.onmessage = function (e) {
|
|
199
|
+
handler.handle(e)
|
|
200
|
+
// handle other messages
|
|
201
|
+
}
|
|
202
|
+
})
|
|
203
|
+
```
|